1adea58f37ba56ee9bd826c974fcdb0b1d890264
[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 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
270   Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
271
272   // update sceneRect
273   // when searching for the first non-date-line we have to take into account that our
274   // model still contains the just removed lines so we cannot simply call updateSceneRect()
275   int numRows = model()->rowCount();
276   QModelIndex firstLineIdx;
277   _firstLineRow = -1;
278   bool needOffset = false;
279   do {
280     _firstLineRow++;
281     if(_firstLineRow >= start && _firstLineRow <= end) {
282       _firstLineRow = end + 1;
283       needOffset = true;
284     }
285     firstLineIdx = model()->index(_firstLineRow, 0);
286   } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
287
288   if(needOffset)
289     _firstLineRow -= end - start + 1;
290   updateSceneRect();
291 }
292
293 void ChatScene::updateForViewport(qreal width, qreal height) {
294   _viewportHeight = height;
295   setWidth(width);
296 }
297
298 void ChatScene::setWidth(qreal width) {
299   if(width == _sceneRect.width())
300     return;
301
302   // clock_t startT = clock();
303
304   // disabling the index while doing this complex updates is about
305   // 2 to 10 times faster!
306   setItemIndexMethod(QGraphicsScene::NoIndex);
307
308   QList<ChatLine *>::iterator lineIter = _lines.end();
309   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
310   qreal linePos = _sceneRect.y() + _sceneRect.height();
311   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
312   while(lineIter != lineIterBegin) {
313     lineIter--;
314     (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
315   }
316   setItemIndexMethod(QGraphicsScene::BspTreeIndex);
317
318   updateSceneRect(width);
319   setHandleXLimits();
320
321 //   clock_t endT = clock();
322 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
323 }
324
325 void ChatScene::firstHandlePositionChanged(qreal xpos) {
326   if(_firstColHandlePos == xpos)
327     return;
328
329   _firstColHandlePos = xpos;
330   ChatViewSettings viewSettings(this);
331   viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
332   ChatViewSettings defaultSettings;
333   defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
334
335   // clock_t startT = clock();
336
337   // disabling the index while doing this complex updates is about
338   // 2 to 10 times faster!
339   setItemIndexMethod(QGraphicsScene::NoIndex);
340
341   QList<ChatLine *>::iterator lineIter = _lines.end();
342   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
343   qreal timestampWidth = firstColumnHandle()->sceneLeft();
344   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
345   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
346
347   while(lineIter != lineIterBegin) {
348     lineIter--;
349     (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
350   }
351   setItemIndexMethod(QGraphicsScene::BspTreeIndex);
352
353   setHandleXLimits();
354
355 //   clock_t endT = clock();
356 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
357 }
358
359 void ChatScene::secondHandlePositionChanged(qreal xpos) {
360   if(_secondColHandlePos == xpos)
361     return;
362
363   _secondColHandlePos = xpos;
364   ChatViewSettings viewSettings(this);
365   viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
366   ChatViewSettings defaultSettings;
367   defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
368
369   // clock_t startT = clock();
370
371   // disabling the index while doing this complex updates is about
372   // 2 to 10 times faster!
373   setItemIndexMethod(QGraphicsScene::NoIndex);
374
375   QList<ChatLine *>::iterator lineIter = _lines.end();
376   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
377   qreal linePos = _sceneRect.y() + _sceneRect.height();
378   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
379   qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
380   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
381   while(lineIter != lineIterBegin) {
382     lineIter--;
383     (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
384   }
385   setItemIndexMethod(QGraphicsScene::BspTreeIndex);
386
387   setHandleXLimits();
388
389 //   clock_t endT = clock();
390 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
391 }
392
393 void ChatScene::setHandleXLimits() {
394   _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
395   _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
396 }
397
398 void ChatScene::setSelectingItem(ChatItem *item) {
399   if(_selectingItem) _selectingItem->clearSelection();
400   _selectingItem = item;
401 }
402
403 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
404   _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
405   _selectionStartCol = _selectionMinCol = item->column();
406   _isSelecting = true;
407   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
408   updateSelection(item->mapToScene(itemPos));
409 }
410
411 void ChatScene::updateSelection(const QPointF &pos) {
412   // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
413   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
414   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, pos.y())));
415   if(!contentItem) return;
416
417   int curRow = contentItem->row();
418   int curColumn;
419   if(pos.x() > _secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
420   else if(pos.x() > _firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
421   else curColumn = ChatLineModel::TimestampColumn;
422
423   ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
424   if(minColumn != _selectionMinCol) {
425     _selectionMinCol = minColumn;
426     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
427       _lines[l]->setSelected(true, minColumn);
428     }
429   }
430   int newstart = qMin(curRow, _firstSelectionRow);
431   int newend = qMax(curRow, _firstSelectionRow);
432   if(newstart < _selectionStart) {
433     for(int l = newstart; l < _selectionStart; l++)
434       _lines[l]->setSelected(true, minColumn);
435   }
436   if(newstart > _selectionStart) {
437     for(int l = _selectionStart; l < newstart; l++)
438       _lines[l]->setSelected(false);
439   }
440   if(newend > _selectionEnd) {
441     for(int l = _selectionEnd+1; l <= newend; l++)
442       _lines[l]->setSelected(true, minColumn);
443   }
444   if(newend < _selectionEnd) {
445     for(int l = newend+1; l <= _selectionEnd; l++)
446       _lines[l]->setSelected(false);
447   }
448
449   _selectionStart = newstart;
450   _selectionEnd = newend;
451   _lastSelectionRow = curRow;
452
453   if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
454     if(!_selectingItem) {
455       qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
456       return;
457     }
458     _lines[curRow]->setSelected(false);
459     _isSelecting = false;
460     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
461   }
462 }
463
464 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
465   if(_isSelecting && event->buttons() == Qt::LeftButton) {
466     updateSelection(event->scenePos());
467     event->accept();
468   } else {
469     QGraphicsScene::mouseMoveEvent(event);
470   }
471 }
472
473 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
474   if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
475     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
476       _lines[l]->setSelected(false);
477     }
478     _selectionStart = -1;
479     QGraphicsScene::mousePressEvent(event);  // so we can start a new local selection
480   } else {
481     QGraphicsScene::mousePressEvent(event);
482   }
483 }
484
485 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
486   if(_isSelecting && !event->buttons() & Qt::LeftButton) {
487     putToClipboard(selectionToString());
488     _isSelecting = false;
489     event->accept();
490   } else {
491     QGraphicsScene::mouseReleaseEvent(event);
492   }
493 }
494
495 void ChatScene::putToClipboard(const QString &selection) {
496   // TODO Configure clipboards
497 #   ifdef Q_WS_X11
498   QApplication::clipboard()->setText(selection, QClipboard::Selection);
499 #   endif
500 //# else
501   QApplication::clipboard()->setText(selection);
502 //# endif
503 }
504
505 //!\brief Convert current selection to human-readable string.
506 QString ChatScene::selectionToString() const {
507   //TODO Make selection format configurable!
508   if(!_isSelecting) return QString();
509   int start = qMin(_selectionStart, _selectionEnd);
510   int end = qMax(_selectionStart, _selectionEnd);
511   if(start < 0 || end >= _lines.count()) {
512     qDebug() << "Invalid selection range:" << start << end;
513     return QString();
514   }
515   QString result;
516   for(int l = start; l <= end; l++) {
517     if(_selectionMinCol == ChatLineModel::TimestampColumn)
518       result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
519     if(_selectionMinCol <= ChatLineModel::SenderColumn)
520       result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
521     result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
522   }
523   return result;
524 }
525
526 void ChatScene::requestBacklog() {
527   static const int REQUEST_COUNT = 500;
528   int backlogSize = model()->rowCount();
529   if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
530     QModelIndex msgIdx = model()->index(0, 0);
531     while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
532       msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
533     }
534     MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
535     BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
536     _lastBacklogSize = backlogSize;
537     Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
538   }
539 }
540
541 int ChatScene::sectionByScenePos(int x) {
542   if(x < _firstColHandle->x())
543     return ChatLineModel::TimestampColumn;
544   if(x < _secondColHandle->x())
545     return ChatLineModel::SenderColumn;
546
547   return ChatLineModel::ContentsColumn;
548 }
549
550 void ChatScene::updateSceneRect(qreal width) {
551   if(_lines.isEmpty()) {
552     updateSceneRect(QRectF(0, 0, width, 0));
553     return;
554   }
555
556   // we hide day change messages at the top by making the scene rect smaller
557   // and by calling QGraphicsItem::hide() on all leading day change messages
558   // the first one is needed to ensure proper scrollbar ranges
559   // the second for cases where the viewport is larger then the set scenerect
560   //  (in this case the items are shown anyways)
561   if(_firstLineRow == -1) {
562     int numRows = model()->rowCount();
563     _firstLineRow = 0;
564     QModelIndex firstLineIdx;
565     while(_firstLineRow < numRows) {
566       firstLineIdx = model()->index(_firstLineRow, 0);
567       if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
568         break;
569       _lines.at(_firstLineRow)->hide();
570       _firstLineRow++;
571     }
572   }
573
574   // the following call should be safe. If it crashes something went wrong during insert/remove
575   ChatLine *firstLine = _lines.at(_firstLineRow);
576   ChatLine *lastLine = _lines.last();
577   updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
578 }
579
580 void ChatScene::updateSceneRect(const QRectF &rect) {
581   _sceneRect = rect;
582   setSceneRect(rect);
583   update();
584 }
585
586 void ChatScene::customEvent(QEvent *event) {
587   switch(event->type()) {
588   default:
589     return;
590   }
591 }
592
593 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
594 #ifndef HAVE_WEBKIT
595   Q_UNUSED(parentItem)
596   Q_UNUSED(url)
597   Q_UNUSED(urlRect)
598 #else
599   if(webPreview.parentItem != parentItem)
600     webPreview.parentItem = parentItem;
601
602   if(webPreview.url != url) {
603     webPreview.url = url;
604     // load a new web view and delete the old one (if exists)
605     if(webPreview.previewItem && webPreview.previewItem->scene()) {
606       removeItem(webPreview.previewItem);
607       delete webPreview.previewItem;
608     }
609     webPreview.previewItem = new WebPreviewItem(url);
610     webPreview.delayTimer.start(2000);
611     webPreview.deleteTimer.stop();
612   } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
613       // we just have to readd the item to the scene
614       webPreview.delayTimer.start(2000);
615       webPreview.deleteTimer.stop();
616   }
617   if(webPreview.urlRect != urlRect) {
618     webPreview.urlRect = urlRect;
619     qreal previewY = urlRect.bottom();
620     qreal previewX = urlRect.x();
621     if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
622       previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
623
624     if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
625       previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
626
627     webPreview.previewItem->setPos(previewX, previewY);
628   }
629 #endif
630 }
631
632 void ChatScene::showWebPreviewEvent() {
633 #ifdef HAVE_WEBKIT
634   if(webPreview.previewItem)
635     addItem(webPreview.previewItem);
636 #endif
637 }
638
639 void ChatScene::clearWebPreview(ChatItem *parentItem) {
640 #ifndef HAVE_WEBKIT
641   Q_UNUSED(parentItem)
642 #else
643   if(parentItem == 0 || webPreview.parentItem == parentItem) {
644     if(webPreview.previewItem && webPreview.previewItem->scene()) {
645       removeItem(webPreview.previewItem);
646       webPreview.deleteTimer.start();
647     }
648     webPreview.delayTimer.stop();
649   }
650 #endif
651 }
652
653 void ChatScene::deleteWebPreviewEvent() {
654 #ifdef HAVE_WEBKIT
655   if(webPreview.previewItem) {
656     delete webPreview.previewItem;
657     webPreview.previewItem = 0;
658   }
659   webPreview.parentItem = 0;
660   webPreview.url = QString();
661   webPreview.urlRect = QRectF();
662 #endif
663 }