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