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