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