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