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