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