you can now disable the web previews and user state icons (settings -> appearance...
[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 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
108   Q_UNUSED(index);
109
110
111 //   QModelIndex sidx = model()->index(start, 2);
112 //   QModelIndex eidx = model()->index(end, 2);
113 //   qDebug() << "rowsInserted:";
114 //   if(start > 0) {
115 //     QModelIndex ssidx = model()->index(start - 1, 2);
116 //     qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
117 //           << ssidx.data(Qt::DisplayRole).toString();
118 //   }
119 //   qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
120 //         << sidx.data(Qt::DisplayRole).toString();
121 //   qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
122 //         << eidx.data(Qt::DisplayRole).toString();
123 //   if(end + 1 < model()->rowCount()) {
124 //     QModelIndex eeidx = model()->index(end + 1, 2);
125 //     qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
126 //           << eeidx.data(Qt::DisplayRole).toString();
127 //   }
128
129   qreal h = 0;
130   qreal y = 0;
131   qreal width = _sceneRect.width();
132   bool atBottom = (start == _lines.count());
133   bool atTop = !atBottom && (start == 0);
134   bool moveTop = false;
135
136   if(start < _lines.count()) {
137     y = _lines.value(start)->y();
138   } else if(atBottom && !_lines.isEmpty()) {
139     y = _lines.last()->y() + _lines.last()->height();
140   }
141
142   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
143   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
144   qreal timestampWidth = firstColumnHandle()->sceneLeft();
145   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
146   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
147
148   if(atTop) {
149     for(int i = end; i >= start; i--) {
150       ChatLine *line = new ChatLine(i, model(),
151                                     width,
152                                     timestampWidth, senderWidth, contentsWidth,
153                                     senderPos, contentsPos);
154       h += line->height();
155       line->setPos(0, y-h);
156       _lines.insert(start, line);
157       addItem(line);
158     }
159   } else {
160     for(int i = start; i <= end; i++) {
161       ChatLine *line = new ChatLine(i, model(),
162                                     width,
163                                     timestampWidth, senderWidth, contentsWidth,
164                                     senderPos, contentsPos);
165       line->setPos(0, y+h);
166       h += line->height();
167       _lines.insert(i, line);
168       addItem(line);
169     }
170   }
171
172   // update existing items
173   for(int i = end+1; i < _lines.count(); i++) {
174     _lines[i]->setRow(i);
175   }
176
177   // update selection
178   if(_selectionStart >= 0) {
179     int offset = end - start + 1;
180     int oldStart = _selectionStart;
181     if(_selectionStart >= start)
182       _selectionStart += offset;
183     if(_selectionEnd >= start) {
184       _selectionEnd += offset;
185       if(_selectionStart == oldStart)
186         for(int i = start; i < start + offset; i++)
187           _lines[i]->setSelected(true);
188     }
189     if(_firstSelectionRow >= start)
190       _firstSelectionRow += offset;
191   }
192
193   // neither pre- or append means we have to do dirty work: move items...
194   int moveStart = 0;
195   int moveEnd = _lines.count() - 1;
196   qreal offset = h;
197   if(!(atTop || atBottom)) {
198     // move top means: moving 0 to end (aka: end + 1)
199     // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
200     if(end + 1 < _lines.count() - end - 1) {
201       // move top part
202       moveTop = true;
203       offset = -offset;
204       moveEnd = end;
205     } else {
206       // move bottom part
207       moveStart = end + 1;
208     }
209     ChatLine *line = 0;
210     for(int i = moveStart; i <= moveEnd; i++) {
211       line = _lines.at(i);
212       line->setPos(0, line->pos().y() + offset);
213     }
214   }
215
216   // check if all went right
217   Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
218 //   if(start != 0) {
219 //     if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
220 //       qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
221 //       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();
222 //       qDebug() << "line[start]" << _lines.at(start)->pos().y();
223 //       qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
224 //       Q_ASSERT(false)
225 //     }
226 //   }
227   Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
228 //   if(end + 1 < _lines.count()) {
229 //     if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
230 //       qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
231 //       qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
232 //       qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
233 //       qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
234 //       Q_ASSERT(false);
235 //     }
236 //   }
237
238   if(!atBottom) {
239     if(start < _firstLineRow) {
240       int prevFirstLineRow = _firstLineRow + (end - start + 1);
241       for(int i = end + 1; i < prevFirstLineRow; i++) {
242         _lines.at(i)->show();
243       }
244     }
245     // force new search for first proper line
246     _firstLineRow = -1;
247   }
248   updateSceneRect();
249   if(atBottom || (!atTop && !moveTop)) {
250     emit lastLineChanged(_lines.last(), h);
251   }
252 }
253
254 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
255   Q_UNUSED(parent);
256
257   qreal h = 0; // total height of removed items;
258
259   bool atTop = (start == 0);
260   bool atBottom = (end == _lines.count() - 1);
261   bool moveTop = false;
262
263   // clear selection
264   if(_selectingItem) {
265     int row = _selectingItem->row();
266     if(row >= start && row <= end)
267       setSelectingItem(0);
268   }
269
270   // remove items from scene
271   QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
272   int lineCount = start;
273   while(lineIter != _lines.end() && lineCount <= end) {
274     h += (*lineIter)->height();
275     delete *lineIter;
276     lineIter = _lines.erase(lineIter);
277     lineCount++;
278   }
279
280   // update rows of remaining chatlines
281   for(int i = start; i < _lines.count(); i++) {
282     _lines.at(i)->setRow(i);
283   }
284
285   // update selection
286   if(_selectionStart >= 0) {
287     int offset = end - start + 1;
288     if(_selectionStart >= start)
289       _selectionStart = qMax(_selectionStart -= offset, start);
290     if(_selectionEnd >= start)
291       _selectionEnd -= offset;
292     if(_firstSelectionRow >= start)
293       _firstSelectionRow -= offset;
294
295     if(_selectionEnd < _selectionStart) {
296       _isSelecting = false;
297       _selectionStart = -1;
298     }
299   }
300
301   // neither removing at bottom or top means we have to move items...
302   if(!(atTop || atBottom)) {
303     qreal offset = h;
304     int moveStart = 0;
305     int moveEnd = _lines.count() - 1;
306     if(start < _lines.count() - start) {
307       // move top part
308       moveTop = true;
309       moveEnd = start - 1;
310     } else {
311       // move bottom part
312       moveStart = start;
313       offset = -offset;
314     }
315     ChatLine *line = 0;
316     for(int i = moveStart; i <= moveEnd; i++) {
317       line = _lines.at(i);
318       line->setPos(0, line->pos().y() + offset);
319     }
320   }
321
322   Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
323
324   // update sceneRect
325   // when searching for the first non-date-line we have to take into account that our
326   // model still contains the just removed lines so we cannot simply call updateSceneRect()
327   int numRows = model()->rowCount();
328   QModelIndex firstLineIdx;
329   _firstLineRow = -1;
330   bool needOffset = false;
331   do {
332     _firstLineRow++;
333     if(_firstLineRow >= start && _firstLineRow <= end) {
334       _firstLineRow = end + 1;
335       needOffset = true;
336     }
337     firstLineIdx = model()->index(_firstLineRow, 0);
338   } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
339
340   if(needOffset)
341     _firstLineRow -= end - start + 1;
342   updateSceneRect();
343 }
344
345 void ChatScene::updateForViewport(qreal width, qreal height) {
346   _viewportHeight = height;
347   setWidth(width);
348 }
349
350 void ChatScene::setWidth(qreal width) {
351   if(width == _sceneRect.width())
352     return;
353
354   // clock_t startT = clock();
355
356   // disabling the index while doing this complex updates is about
357   // 2 to 10 times faster!
358   //setItemIndexMethod(QGraphicsScene::NoIndex);
359
360   QList<ChatLine *>::iterator lineIter = _lines.end();
361   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
362   qreal linePos = _sceneRect.y() + _sceneRect.height();
363   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
364   while(lineIter != lineIterBegin) {
365     lineIter--;
366     (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
367   }
368   //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
369
370   updateSceneRect(width);
371   setHandleXLimits();
372   emit layoutChanged();
373
374 //   clock_t endT = clock();
375 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
376 }
377
378 void ChatScene::firstHandlePositionChanged(qreal xpos) {
379   if(_firstColHandlePos == xpos)
380     return;
381
382   _firstColHandlePos = xpos;
383   ChatViewSettings viewSettings(this);
384   viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
385   ChatViewSettings defaultSettings;
386   defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
387
388   // clock_t startT = clock();
389
390   // disabling the index while doing this complex updates is about
391   // 2 to 10 times faster!
392   //setItemIndexMethod(QGraphicsScene::NoIndex);
393
394   QList<ChatLine *>::iterator lineIter = _lines.end();
395   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
396   qreal timestampWidth = firstColumnHandle()->sceneLeft();
397   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
398   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
399
400   while(lineIter != lineIterBegin) {
401     lineIter--;
402     (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
403   }
404   //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
405
406   setHandleXLimits();
407
408 //   clock_t endT = clock();
409 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
410 }
411
412 void ChatScene::secondHandlePositionChanged(qreal xpos) {
413   if(_secondColHandlePos == xpos)
414     return;
415
416   _secondColHandlePos = xpos;
417   ChatViewSettings viewSettings(this);
418   viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
419   ChatViewSettings defaultSettings;
420   defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
421
422   // clock_t startT = clock();
423
424   // disabling the index while doing this complex updates is about
425   // 2 to 10 times faster!
426   //setItemIndexMethod(QGraphicsScene::NoIndex);
427
428   QList<ChatLine *>::iterator lineIter = _lines.end();
429   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
430   qreal linePos = _sceneRect.y() + _sceneRect.height();
431   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
432   qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
433   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
434   while(lineIter != lineIterBegin) {
435     lineIter--;
436     (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
437   }
438   //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
439
440   updateSceneRect();
441   setHandleXLimits();
442   emit layoutChanged();
443
444 //   clock_t endT = clock();
445 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
446 }
447
448 void ChatScene::setHandleXLimits() {
449   _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
450   _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
451 }
452
453 void ChatScene::setSelectingItem(ChatItem *item) {
454   if(_selectingItem) _selectingItem->clearSelection();
455   _selectingItem = item;
456 }
457
458 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
459   _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
460   _selectionStartCol = _selectionMinCol = item->column();
461   _isSelecting = true;
462   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
463   updateSelection(item->mapToScene(itemPos));
464 }
465
466 void ChatScene::updateSelection(const QPointF &pos) {
467   // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
468   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
469   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, pos.y())));
470   if(!contentItem) return;
471
472   int curRow = contentItem->row();
473   int curColumn;
474   if(pos.x() > _secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
475   else if(pos.x() > _firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
476   else curColumn = ChatLineModel::TimestampColumn;
477
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 int ChatScene::sectionByScenePos(int 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 void ChatScene::updateSceneRect(qreal width) {
608   if(_lines.isEmpty()) {
609     updateSceneRect(QRectF(0, 0, width, 0));
610     return;
611   }
612
613   // we hide day change messages at the top by making the scene rect smaller
614   // and by calling QGraphicsItem::hide() on all leading day change messages
615   // the first one is needed to ensure proper scrollbar ranges
616   // the second for cases where the viewport is larger then the set scenerect
617   //  (in this case the items are shown anyways)
618   if(_firstLineRow == -1) {
619     int numRows = model()->rowCount();
620     _firstLineRow = 0;
621     QModelIndex firstLineIdx;
622     while(_firstLineRow < numRows) {
623       firstLineIdx = model()->index(_firstLineRow, 0);
624       if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
625         break;
626       _lines.at(_firstLineRow)->hide();
627       _firstLineRow++;
628     }
629   }
630
631   // the following call should be safe. If it crashes something went wrong during insert/remove
632   if(_firstLineRow < _lines.count()) {
633     ChatLine *firstLine = _lines.at(_firstLineRow);
634     ChatLine *lastLine = _lines.last();
635     updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
636   } else {
637     // empty scene rect
638     updateSceneRect(QRectF(0, 0, width, 0));
639   }
640 }
641
642 void ChatScene::updateSceneRect(const QRectF &rect) {
643   _sceneRect = rect;
644   setSceneRect(rect);
645   update();
646 }
647
648 bool ChatScene::event(QEvent *e) {
649   if(e->type() == QEvent::ApplicationPaletteChange) {
650     _firstColHandle->setColor(QApplication::palette().windowText().color());
651     _secondColHandle->setColor(QApplication::palette().windowText().color());
652   }
653   return QGraphicsScene::event(e);
654 }
655
656 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
657 #ifndef HAVE_WEBKIT
658   Q_UNUSED(parentItem)
659   Q_UNUSED(url)
660   Q_UNUSED(urlRect)
661 #else
662   if(!_showWebPreview)
663     return;
664
665   if(webPreview.parentItem != parentItem)
666     webPreview.parentItem = parentItem;
667
668   if(webPreview.url != url) {
669     webPreview.url = url;
670     // load a new web view and delete the old one (if exists)
671     if(webPreview.previewItem && webPreview.previewItem->scene()) {
672       removeItem(webPreview.previewItem);
673       delete webPreview.previewItem;
674     }
675     webPreview.previewItem = new WebPreviewItem(url);
676     webPreview.delayTimer.start(2000);
677     webPreview.deleteTimer.stop();
678   } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
679       // we just have to readd the item to the scene
680       webPreview.delayTimer.start(2000);
681       webPreview.deleteTimer.stop();
682   }
683   if(webPreview.urlRect != urlRect) {
684     webPreview.urlRect = urlRect;
685     qreal previewY = urlRect.bottom();
686     qreal previewX = urlRect.x();
687     if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
688       previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
689
690     if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
691       previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
692
693     webPreview.previewItem->setPos(previewX, previewY);
694   }
695 #endif
696 }
697
698 void ChatScene::showWebPreviewEvent() {
699 #ifdef HAVE_WEBKIT
700   if(webPreview.previewItem)
701     addItem(webPreview.previewItem);
702 #endif
703 }
704
705 void ChatScene::clearWebPreview(ChatItem *parentItem) {
706 #ifndef HAVE_WEBKIT
707   Q_UNUSED(parentItem)
708 #else
709   if(parentItem == 0 || webPreview.parentItem == parentItem) {
710     if(webPreview.previewItem && webPreview.previewItem->scene()) {
711       removeItem(webPreview.previewItem);
712       webPreview.deleteTimer.start();
713     }
714     webPreview.delayTimer.stop();
715   }
716 #endif
717 }
718
719 void ChatScene::deleteWebPreviewEvent() {
720 #ifdef HAVE_WEBKIT
721   if(webPreview.previewItem) {
722     delete webPreview.previewItem;
723     webPreview.previewItem = 0;
724   }
725   webPreview.parentItem = 0;
726   webPreview.url = QString();
727   webPreview.urlRect = QRectF();
728 #endif
729 }
730
731 void ChatScene::showWebPreviewChanged() {
732   ChatViewSettings settings;
733   _showWebPreview = settings.showWebPreview();
734 }