fixing crash on disconnect
[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 #include "webpreviewitem.h"
38
39 const qreal minContentsWidth = 200;
40
41 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
42   : QGraphicsScene(0, 0, width, 0, parent),
43     _idString(idString),
44     _model(model),
45     _singleBufferScene(false),
46     _sceneRect(0, 0, width, 0),
47     _viewportHeight(0),
48     _selectingItem(0),
49     _selectionStart(-1),
50     _isSelecting(false),
51     _lastBacklogSize(0)
52 {
53   MessageFilter *filter = qobject_cast<MessageFilter*>(model);
54   if(filter) {
55     _singleBufferScene = filter->isSingleBufferFilter();
56   }
57
58   ChatViewSettings defaultSettings;
59   int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
60   int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
61
62   ChatViewSettings viewSettings(this);
63   firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
64   secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
65
66   firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
67   addItem(firstColHandle);
68   firstColHandle->setXPos(firstColHandlePos);
69   connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
70   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
71
72   secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
73   addItem(secondColHandle);
74   secondColHandle->setXPos(secondColHandlePos);
75   connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
76   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
77
78   setHandleXLimits();
79
80   connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
81           this, SLOT(rowsInserted(const QModelIndex &, int, int)));
82   connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
83           this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
84
85   if(model->rowCount() > 0)
86     rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
87 }
88
89 ChatScene::~ChatScene() {
90 }
91
92 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
93   Q_UNUSED(index);
94
95   clearWebPreview();
96
97 //   QModelIndex sidx = model()->index(start, 0);
98 //   QModelIndex eidx = model()->index(end, 0);
99 //   qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
100
101   qreal h = 0;
102   qreal y = _sceneRect.y();
103   qreal width = _sceneRect.width();
104   bool atTop = true;
105   bool atBottom = false;
106   bool moveTop = false;
107
108   if(start > 0 && start < _lines.count()) {
109     y = _lines.value(start)->y();
110     atTop = false;
111   }
112   if(start == _lines.count()) {
113     y = _sceneRect.bottom();
114     atTop = false;
115     atBottom = true;
116   }
117
118   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
119   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
120   qreal timestampWidth = firstColumnHandle()->sceneLeft();
121   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
122   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
123
124   for(int i = start; i <= end; i++) {
125     ChatLine *line = new ChatLine(i, model(),
126                                   width,
127                                   timestampWidth, senderWidth, contentsWidth,
128                                   senderPos, contentsPos);
129     line->setPos(0, y+h);
130     h += line->height();
131     _lines.insert(i, line);
132     addItem(line);
133   }
134
135   // update existing items
136   for(int i = end+1; i < _lines.count(); i++) {
137     _lines[i]->setRow(i);
138   }
139
140   // update selection
141   if(_selectionStart >= 0) {
142     int offset = end - start + 1;
143     if(_selectionStart >= start) _selectionStart += offset;
144     if(_selectionEnd >= start) _selectionEnd += offset;
145     if(_firstSelectionRow >= start) _firstSelectionRow += offset;
146     if(_lastSelectionRow >= start) _lastSelectionRow += offset;
147   }
148
149   // neither pre- or append means we have to do dirty work: move items...
150   if(!(atTop || atBottom)) {
151     qreal offset = h;
152     int moveStart = 0;
153     int moveEnd = _lines.count() - 1;
154     // move top means: moving 0 to end (aka: end + 1)
155     // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
156     if(end + 1 < _lines.count() - end - 1) {
157       // move top part
158       moveTop = true;
159       offset = -offset;
160       moveEnd = end;
161     } else {
162       // move bottom part
163       moveStart = start;
164     }
165     ChatLine *line = 0;
166     for(int i = moveStart; i <= moveEnd; i++) {
167       line = _lines.at(i);
168       line->setPos(0, line->pos().y() + offset);
169     }
170   }
171
172   updateSceneRect();
173   if(atBottom) {
174     emit lastLineChanged(_lines.last());
175   }
176
177 }
178
179 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
180   Q_UNUSED(parent);
181
182   clearWebPreview();
183
184   qreal h = 0; // total height of removed items;
185
186   bool atTop = (start == 0);
187   bool atBottom = (end == _lines.count() - 1);
188   bool moveTop = false;
189
190   // remove items from scene
191   QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
192   int lineCount = start;
193   while(lineIter != _lines.end() && lineCount <= end) {
194     h += (*lineIter)->height();
195     delete *lineIter;
196     lineIter = _lines.erase(lineIter);
197     lineCount++;
198   }
199
200   // update rows of remaining chatlines
201   for(int i = start; i < _lines.count(); i++) {
202     _lines.at(i)->setRow(i);
203   }
204
205   // update selection
206   if(_selectionStart >= 0) {
207     int offset = end - start + 1;
208     if(_selectionStart >= start)
209       _selectionStart -= offset;
210     if(_selectionEnd >= start)
211       _selectionEnd -= offset;
212     if(_firstSelectionRow >= start)
213       _firstSelectionRow -= offset;
214     if(_lastSelectionRow >= start)
215       _lastSelectionRow -= offset;
216   }
217
218   // neither removing at bottom or top means we have to move items...
219   if(!(atTop || atBottom)) {
220     qreal offset = h;
221     int moveStart = 0;
222     int moveEnd = _lines.count() - 1;
223     if(start < _lines.count() - start) {
224       // move top part
225       moveTop = true;
226       moveEnd = start - 1;
227     } else {
228       // move bottom part
229       moveStart = start;
230       offset = -offset;
231     }
232     ChatLine *line = 0;
233     for(int i = moveStart; i <= moveEnd; i++) {
234       line = _lines.at(i);
235       line->setPos(0, line->pos().y() + offset);
236     }
237   }
238
239
240   // update sceneRect
241   // when searching for the first non-date-line we have to take into account that our
242   // model still contains the just removed lines so we cannot simply call updateSceneRect()
243   if(_lines.isEmpty()) {
244     updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
245     return;
246   }
247   int numRows = model()->rowCount();
248   QModelIndex firstLineIdx;
249   int row = -1;
250   bool needOffset = false;
251   do {
252     row++;
253     if(row >= start && row <= end) {
254       row = end + 1;
255       needOffset = true;
256     }
257     firstLineIdx = model()->index(row, 0);
258   } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && row < numRows);
259
260   if(needOffset)
261     row -= end - start + 1;
262
263   ChatLine *firstLine = _lines.at(row);
264   ChatLine *lastLine = _lines.last();
265
266   updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
267 }
268
269 void ChatScene::updateForViewport(qreal width, qreal height) {
270   _viewportHeight = height;
271   setWidth(width);
272 }
273
274 // setWidth is used for 2 things:
275 //  a) updating the scene to fit the width of the corresponding view
276 //  b) to update the positions of the items if a columhandle has changed it's position
277 // forceReposition is true in the second case
278 // this method features some codeduplication for the sake of performance
279 void ChatScene::setWidth(qreal width, bool forceReposition) {
280   if(width == _sceneRect.width() && !forceReposition)
281     return;
282
283 //   clock_t startT = clock();
284
285   qreal linePos = _sceneRect.y() + _sceneRect.height();
286   QList<ChatLine *>::iterator lineIter = _lines.end();
287   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
288   ChatLine *line = 0;
289   qreal lineHeight = 0;
290   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
291
292   if(forceReposition) {
293     qreal timestampWidth = firstColumnHandle()->sceneLeft();
294     qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
295     QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
296     QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
297     while(lineIter != lineIterBegin) {
298       lineIter--;
299       line = *lineIter;
300       lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
301       linePos -= lineHeight;
302       line->setPos(0, linePos);
303     }
304   } else {
305     while(lineIter != lineIterBegin) {
306       lineIter--;
307       line = *lineIter;
308       lineHeight = line->setGeometryByWidth(width, contentsWidth);
309       linePos -= lineHeight;
310       line->setPos(0, linePos);
311     }
312   }
313
314   updateSceneRect(width);
315   setHandleXLimits();
316
317 //   clock_t endT = clock();
318 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
319 }
320
321 void ChatScene::handlePositionChanged(qreal xpos) {
322   bool first = (sender() == firstColHandle);
323   qreal oldx;
324   if(first) {
325     oldx = firstColHandlePos;
326     firstColHandlePos = xpos;
327   } else {
328     oldx = secondColHandlePos;
329     secondColHandlePos = xpos;
330   }
331
332   ChatViewSettings viewSettings(this);
333   viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
334   viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
335
336   ChatViewSettings defaultSettings;
337   defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
338   defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
339
340   setWidth(width(), true);  // readjust all chatlines
341   // we get ugly redraw errors if we don't update this explicitly... :(
342   // width() should be the same for both handles, so just use firstColHandle regardless
343   //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
344 }
345
346 void ChatScene::setHandleXLimits() {
347   firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
348   secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
349 }
350
351 void ChatScene::setSelectingItem(ChatItem *item) {
352   if(_selectingItem) _selectingItem->clearSelection();
353   _selectingItem = item;
354 }
355
356 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
357   _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
358   _selectionStartCol = _selectionMinCol = item->column();
359   _isSelecting = true;
360   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
361   updateSelection(item->mapToScene(itemPos));
362 }
363
364 void ChatScene::updateSelection(const QPointF &pos) {
365   // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
366   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
367   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
368   if(!contentItem) return;
369
370   int curRow = contentItem->row();
371   int curColumn;
372   if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
373   else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
374   else curColumn = ChatLineModel::TimestampColumn;
375
376   ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
377   if(minColumn != _selectionMinCol) {
378     _selectionMinCol = minColumn;
379     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
380       _lines[l]->setSelected(true, minColumn);
381     }
382   }
383   int newstart = qMin(curRow, _firstSelectionRow);
384   int newend = qMax(curRow, _firstSelectionRow);
385   if(newstart < _selectionStart) {
386     for(int l = newstart; l < _selectionStart; l++)
387       _lines[l]->setSelected(true, minColumn);
388   }
389   if(newstart > _selectionStart) {
390     for(int l = _selectionStart; l < newstart; l++)
391       _lines[l]->setSelected(false);
392   }
393   if(newend > _selectionEnd) {
394     for(int l = _selectionEnd+1; l <= newend; l++)
395       _lines[l]->setSelected(true, minColumn);
396   }
397   if(newend < _selectionEnd) {
398     for(int l = newend+1; l <= _selectionEnd; l++)
399       _lines[l]->setSelected(false);
400   }
401
402   _selectionStart = newstart;
403   _selectionEnd = newend;
404   _lastSelectionRow = curRow;
405
406   if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
407     if(!_selectingItem) {
408       qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
409       return;
410     }
411     _lines[curRow]->setSelected(false);
412     _isSelecting = false;
413     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
414   }
415 }
416
417 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
418   if(_isSelecting && event->buttons() == Qt::LeftButton) {
419     updateSelection(event->scenePos());
420     event->accept();
421   } else {
422     QGraphicsScene::mouseMoveEvent(event);
423   }
424 }
425
426 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
427   if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
428     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
429       _lines[l]->setSelected(false);
430     }
431     _selectionStart = -1;
432     QGraphicsScene::mousePressEvent(event);  // so we can start a new local selection
433   } else {
434     QGraphicsScene::mousePressEvent(event);
435   }
436 }
437
438 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
439   if(_isSelecting && !event->buttons() & Qt::LeftButton) {
440     putToClipboard(selectionToString());
441     _isSelecting = false;
442     event->accept();
443   } else {
444     QGraphicsScene::mouseReleaseEvent(event);
445   }
446 }
447
448 void ChatScene::putToClipboard(const QString &selection) {
449   // TODO Configure clipboards
450 #   ifdef Q_WS_X11
451   QApplication::clipboard()->setText(selection, QClipboard::Selection);
452 #   endif
453 //# else
454   QApplication::clipboard()->setText(selection);
455 //# endif
456 }
457
458 //!\brief Convert current selection to human-readable string.
459 QString ChatScene::selectionToString() const {
460   //TODO Make selection format configurable!
461   if(!_isSelecting) return QString();
462   int start = qMin(_selectionStart, _selectionEnd);
463   int end = qMax(_selectionStart, _selectionEnd);
464   if(start < 0 || end >= _lines.count()) {
465     qDebug() << "Invalid selection range:" << start << end;
466     return QString();
467   }
468   QString result;
469   for(int l = start; l <= end; l++) {
470     if(_selectionMinCol == ChatLineModel::TimestampColumn)
471       result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
472     if(_selectionMinCol <= ChatLineModel::SenderColumn)
473       result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
474     result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
475   }
476   return result;
477 }
478
479 void ChatScene::requestBacklog() {
480   static const int REQUEST_COUNT = 500;
481   int backlogSize = model()->rowCount();
482   if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
483     QModelIndex msgIdx = model()->index(0, 0);
484     while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
485       msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
486     }
487     MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
488     BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
489     _lastBacklogSize = backlogSize;
490     Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
491   }
492 }
493
494 int ChatScene::sectionByScenePos(int x) {
495   if(x < firstColHandle->x())
496     return ChatLineModel::TimestampColumn;
497   if(x < secondColHandle->x())
498     return ChatLineModel::SenderColumn;
499
500   return ChatLineModel::ContentsColumn;
501 }
502
503 void ChatScene::updateSceneRect() {
504   if(_lines.isEmpty())
505     return;
506
507   // we hide day change messages at the top by making the scene rect smaller
508   int numRows = model()->rowCount();
509   int row = -1;
510   QModelIndex firstLineIdx;
511   do {
512     row++;
513     firstLineIdx = model()->index(row, 0);
514   } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && row < numRows);
515
516   // the following call should be safe. If it crashes something went wrong during insert/remove
517   ChatLine *firstLine = _lines.at(row);
518   ChatLine *lastLine = _lines.last();
519
520   updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
521 }
522
523 void ChatScene::updateSceneRect(qreal width) {
524   _sceneRect.setWidth(width);
525   updateSceneRect();
526 }
527
528 void ChatScene::updateSceneRect(const QRectF &rect) {
529   _sceneRect = rect;
530   setSceneRect(rect);
531 }
532
533
534 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
535 #ifndef HAVE_WEBKIT
536   Q_UNUSED(parentItem)
537   Q_UNUSED(url)
538   Q_UNUSED(urlRect)
539 #else
540   if(webPreview.parentItem != parentItem)
541     webPreview.parentItem = parentItem;
542
543   if(webPreview.url != url) {
544     webPreview.url = url;
545     // load a new web view and delete the old one (if exists)
546     if(webPreview.previewItem) {
547       removeItem(webPreview.previewItem);
548       delete webPreview.previewItem;
549     }
550     webPreview.previewItem = new WebPreviewItem(url);
551     addItem(webPreview.previewItem);
552   }
553   if(webPreview.urlRect != urlRect) {
554     webPreview.urlRect = urlRect;
555     qreal previewY = urlRect.bottom();
556     qreal previewX = urlRect.x();
557     if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
558       previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
559
560     if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
561       previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
562
563     webPreview.previewItem->setPos(previewX, previewY);
564   }
565 #endif
566 }
567
568 void ChatScene::clearWebPreview(ChatItem *parentItem) {
569 #ifndef HAVE_WEBKIT
570   Q_UNUSED(parentItem)
571 #else
572   if(parentItem == 0 || webPreview.parentItem == parentItem) {
573     if(webPreview.previewItem) {
574       removeItem(webPreview.previewItem);
575       delete webPreview.previewItem;
576       webPreview.previewItem = 0;
577     }
578     webPreview.parentItem = 0;
579     webPreview.url = QString();
580     webPreview.urlRect = QRectF();
581   }
582 #endif
583 }