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