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