313d80eb3c2806266e8ecb3fcccd17e2cb102c28
[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 <QDrag>
24 #include <QGraphicsSceneMouseEvent>
25 #include <QPersistentModelIndex>
26 #include <QWebView>
27
28 #include "chatitem.h"
29 #include "chatline.h"
30 #include "chatlinemodelitem.h"
31 #include "chatscene.h"
32 #include "client.h"
33 #include "clientbacklogmanager.h"
34 #include "columnhandleitem.h"
35 #include "messagefilter.h"
36 #include "qtui.h"
37 #include "qtuistyle.h"
38 #include "chatviewsettings.h"
39 #include "webpreviewitem.h"
40
41 const qreal minContentsWidth = 200;
42
43 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
44   : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
45     _chatView(parent),
46     _idString(idString),
47     _model(model),
48     _singleBufferScene(false),
49     _sceneRect(0, 0, width, 0),
50     _firstLineRow(-1),
51     _viewportHeight(0),
52     _cutoffMode(CutoffRight),
53     _selectingItem(0),
54     _selectionStart(-1),
55     _isSelecting(false),
56     _clickMode(NoClick),
57     _clickHandled(true),
58     _leftButtonPressed(false)
59 {
60   MessageFilter *filter = qobject_cast<MessageFilter*>(model);
61   if(filter) {
62     _singleBufferScene = filter->isSingleBufferFilter();
63   }
64
65   ChatViewSettings defaultSettings;
66   int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
67   int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
68
69   ChatViewSettings viewSettings(this);
70   _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
71   _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
72
73   _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
74   addItem(_firstColHandle);
75   _firstColHandle->setXPos(_firstColHandlePos);
76   connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
77   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
78
79   _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
80   addItem(_secondColHandle);
81   _secondColHandle->setXPos(_secondColHandlePos);
82   connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
83
84   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
85
86   setHandleXLimits();
87
88   connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
89           this, SLOT(rowsInserted(const QModelIndex &, int, int)));
90   connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
91           this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
92
93   if(model->rowCount() > 0)
94     rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
95
96 #ifdef HAVE_WEBKIT
97   webPreview.delayTimer.setSingleShot(true);
98   connect(&webPreview.delayTimer, SIGNAL(timeout()), this, SLOT(showWebPreviewEvent()));
99   //webPreview.deleteTimer.setInterval(600000);
100   webPreview.deleteTimer.setInterval(10000);
101   connect(&webPreview.deleteTimer, SIGNAL(timeout()), this, SLOT(deleteWebPreviewEvent()));
102 #endif
103   _showWebPreview = defaultSettings.showWebPreview();
104   defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
105
106   _clickTimer.setInterval(QApplication::doubleClickInterval());
107   _clickTimer.setSingleShot(true);
108   connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
109
110   setItemIndexMethod(QGraphicsScene::NoIndex);
111 }
112
113 ChatScene::~ChatScene() {
114 }
115
116 ChatView *ChatScene::chatView() const {
117   return _chatView;
118 }
119
120 ColumnHandleItem *ChatScene::firstColumnHandle() const {
121   return _firstColHandle;
122 }
123
124 ColumnHandleItem *ChatScene::secondColumnHandle() const {
125   return _secondColHandle;
126 }
127
128 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
129   QGraphicsItem *item = itemAt(scenePos);
130   return dynamic_cast<ChatItem *>(item);
131 }
132
133 bool ChatScene::containsBuffer(const BufferId &id) const {
134   MessageFilter *filter = qobject_cast<MessageFilter*>(model());
135   if(filter)
136     return filter->containsBuffer(id);
137   else
138     return false;
139 }
140
141 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
142   Q_UNUSED(index);
143
144
145 //   QModelIndex sidx = model()->index(start, 2);
146 //   QModelIndex eidx = model()->index(end, 2);
147 //   qDebug() << "rowsInserted:";
148 //   if(start > 0) {
149 //     QModelIndex ssidx = model()->index(start - 1, 2);
150 //     qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
151 //           << ssidx.data(Qt::DisplayRole).toString();
152 //   }
153 //   qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
154 //         << sidx.data(Qt::DisplayRole).toString();
155 //   qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
156 //         << eidx.data(Qt::DisplayRole).toString();
157 //   if(end + 1 < model()->rowCount()) {
158 //     QModelIndex eeidx = model()->index(end + 1, 2);
159 //     qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
160 //           << eeidx.data(Qt::DisplayRole).toString();
161 //   }
162
163   qreal h = 0;
164   qreal y = 0;
165   qreal width = _sceneRect.width();
166   bool atBottom = (start == _lines.count());
167   bool atTop = !atBottom && (start == 0);
168   bool moveTop = false;
169
170   if(start < _lines.count()) {
171     y = _lines.value(start)->y();
172   } else if(atBottom && !_lines.isEmpty()) {
173     y = _lines.last()->y() + _lines.last()->height();
174   }
175
176   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
177   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
178   qreal timestampWidth = firstColumnHandle()->sceneLeft();
179   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
180   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
181
182   if(atTop) {
183     for(int i = end; i >= start; i--) {
184       ChatLine *line = new ChatLine(i, model(),
185                                     width,
186                                     timestampWidth, senderWidth, contentsWidth,
187                                     senderPos, contentsPos);
188       h += line->height();
189       line->setPos(0, y-h);
190       _lines.insert(start, line);
191       addItem(line);
192     }
193   } else {
194     for(int i = start; i <= end; i++) {
195       ChatLine *line = new ChatLine(i, model(),
196                                     width,
197                                     timestampWidth, senderWidth, contentsWidth,
198                                     senderPos, contentsPos);
199       line->setPos(0, y+h);
200       h += line->height();
201       _lines.insert(i, line);
202       addItem(line);
203     }
204   }
205
206   // update existing items
207   for(int i = end+1; i < _lines.count(); i++) {
208     _lines[i]->setRow(i);
209   }
210
211   // update selection
212   if(_selectionStart >= 0) {
213     int offset = end - start + 1;
214     int oldStart = _selectionStart;
215     if(_selectionStart >= start)
216       _selectionStart += offset;
217     if(_selectionEnd >= start) {
218       _selectionEnd += offset;
219       if(_selectionStart == oldStart)
220         for(int i = start; i < start + offset; i++)
221           _lines[i]->setSelected(true);
222     }
223     if(_firstSelectionRow >= start)
224       _firstSelectionRow += offset;
225   }
226
227   // neither pre- or append means we have to do dirty work: move items...
228   int moveStart = 0;
229   int moveEnd = _lines.count() - 1;
230   qreal offset = h;
231   if(!(atTop || atBottom)) {
232     // move top means: moving 0 to end (aka: end + 1)
233     // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
234     if(end + 1 < _lines.count() - end - 1) {
235       // move top part
236       moveTop = true;
237       offset = -offset;
238       moveEnd = end;
239     } else {
240       // move bottom part
241       moveStart = end + 1;
242     }
243     ChatLine *line = 0;
244     for(int i = moveStart; i <= moveEnd; i++) {
245       line = _lines.at(i);
246       line->setPos(0, line->pos().y() + offset);
247     }
248   }
249
250   // check if all went right
251   Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
252 //   if(start != 0) {
253 //     if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
254 //       qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
255 //       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();
256 //       qDebug() << "line[start]" << _lines.at(start)->pos().y();
257 //       qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
258 //       Q_ASSERT(false)
259 //     }
260 //   }
261   Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
262 //   if(end + 1 < _lines.count()) {
263 //     if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
264 //       qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
265 //       qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
266 //       qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
267 //       qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
268 //       Q_ASSERT(false);
269 //     }
270 //   }
271
272   if(!atBottom) {
273     if(start < _firstLineRow) {
274       int prevFirstLineRow = _firstLineRow + (end - start + 1);
275       for(int i = end + 1; i < prevFirstLineRow; i++) {
276         _lines.at(i)->show();
277       }
278     }
279     // force new search for first proper line
280     _firstLineRow = -1;
281   }
282   updateSceneRect();
283   if(atBottom || (!atTop && !moveTop)) {
284     emit lastLineChanged(_lines.last(), h);
285   }
286 }
287
288 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
289   Q_UNUSED(parent);
290
291   qreal h = 0; // total height of removed items;
292
293   bool atTop = (start == 0);
294   bool atBottom = (end == _lines.count() - 1);
295   bool moveTop = false;
296
297   // clear selection
298   if(_selectingItem) {
299     int row = _selectingItem->row();
300     if(row >= start && row <= end)
301       setSelectingItem(0);
302   }
303
304   // remove items from scene
305   QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
306   int lineCount = start;
307   while(lineIter != _lines.end() && lineCount <= end) {
308     h += (*lineIter)->height();
309     delete *lineIter;
310     lineIter = _lines.erase(lineIter);
311     lineCount++;
312   }
313
314   // update rows of remaining chatlines
315   for(int i = start; i < _lines.count(); i++) {
316     _lines.at(i)->setRow(i);
317   }
318
319   // update selection
320   if(_selectionStart >= 0) {
321     int offset = end - start + 1;
322     if(_selectionStart >= start)
323       _selectionStart = qMax(_selectionStart -= offset, start);
324     if(_selectionEnd >= start)
325       _selectionEnd -= offset;
326     if(_firstSelectionRow >= start)
327       _firstSelectionRow -= offset;
328
329     if(_selectionEnd < _selectionStart) {
330       _isSelecting = false;
331       _selectionStart = -1;
332     }
333   }
334
335   // neither removing at bottom or top means we have to move items...
336   if(!(atTop || atBottom)) {
337     qreal offset = h;
338     int moveStart = 0;
339     int moveEnd = _lines.count() - 1;
340     if(start < _lines.count() - start) {
341       // move top part
342       moveTop = true;
343       moveEnd = start - 1;
344     } else {
345       // move bottom part
346       moveStart = start;
347       offset = -offset;
348     }
349     ChatLine *line = 0;
350     for(int i = moveStart; i <= moveEnd; i++) {
351       line = _lines.at(i);
352       line->setPos(0, line->pos().y() + offset);
353     }
354   }
355
356   Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
357
358   // update sceneRect
359   // when searching for the first non-date-line we have to take into account that our
360   // model still contains the just removed lines so we cannot simply call updateSceneRect()
361   int numRows = model()->rowCount();
362   QModelIndex firstLineIdx;
363   _firstLineRow = -1;
364   bool needOffset = false;
365   do {
366     _firstLineRow++;
367     if(_firstLineRow >= start && _firstLineRow <= end) {
368       _firstLineRow = end + 1;
369       needOffset = true;
370     }
371     firstLineIdx = model()->index(_firstLineRow, 0);
372   } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
373
374   if(needOffset)
375     _firstLineRow -= end - start + 1;
376   updateSceneRect();
377 }
378
379 void ChatScene::updateForViewport(qreal width, qreal height) {
380   _viewportHeight = height;
381   setWidth(width);
382 }
383
384 void ChatScene::setWidth(qreal width) {
385   if(width == _sceneRect.width())
386     return;
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 linePos = _sceneRect.y() + _sceneRect.height();
397   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
398   while(lineIter != lineIterBegin) {
399     lineIter--;
400     (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
401   }
402   //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
403
404   updateSceneRect(width);
405   setHandleXLimits();
406   emit layoutChanged();
407
408 //   clock_t endT = clock();
409 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
410 }
411
412 void ChatScene::firstHandlePositionChanged(qreal xpos) {
413   if(_firstColHandlePos == xpos)
414     return;
415
416   _firstColHandlePos = xpos;
417   ChatViewSettings viewSettings(this);
418   viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
419   ChatViewSettings defaultSettings;
420   defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
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 timestampWidth = firstColumnHandle()->sceneLeft();
431   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
432   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
433
434   while(lineIter != lineIterBegin) {
435     lineIter--;
436     (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
437   }
438   //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
439
440   setHandleXLimits();
441
442 //   clock_t endT = clock();
443 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
444 }
445
446 void ChatScene::secondHandlePositionChanged(qreal xpos) {
447   if(_secondColHandlePos == xpos)
448     return;
449
450   _secondColHandlePos = xpos;
451   ChatViewSettings viewSettings(this);
452   viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
453   ChatViewSettings defaultSettings;
454   defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
455
456   // clock_t startT = clock();
457
458   // disabling the index while doing this complex updates is about
459   // 2 to 10 times faster!
460   //setItemIndexMethod(QGraphicsScene::NoIndex);
461
462   QList<ChatLine *>::iterator lineIter = _lines.end();
463   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
464   qreal linePos = _sceneRect.y() + _sceneRect.height();
465   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
466   qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
467   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
468   while(lineIter != lineIterBegin) {
469     lineIter--;
470     (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
471   }
472   //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
473
474   updateSceneRect();
475   setHandleXLimits();
476   emit layoutChanged();
477
478 //   clock_t endT = clock();
479 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
480 }
481
482 void ChatScene::setHandleXLimits() {
483   _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
484   _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
485 }
486
487 void ChatScene::setSelectingItem(ChatItem *item) {
488   if(_selectingItem) _selectingItem->clearSelection();
489   _selectingItem = item;
490 }
491
492 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
493   _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
494   _selectionStartCol = _selectionMinCol = item->column();
495   _isSelecting = true;
496   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
497   updateSelection(item->mapToScene(itemPos));
498 }
499
500 void ChatScene::updateSelection(const QPointF &pos) {
501   int curRow = rowByScenePos(pos);
502   if(curRow < 0) return;
503   int curColumn = (int)columnByScenePos(pos);
504   ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
505   if(minColumn != _selectionMinCol) {
506     _selectionMinCol = minColumn;
507     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
508       _lines[l]->setSelected(true, minColumn);
509     }
510   }
511   int newstart = qMin(curRow, _firstSelectionRow);
512   int newend = qMax(curRow, _firstSelectionRow);
513   if(newstart < _selectionStart) {
514     for(int l = newstart; l < _selectionStart; l++)
515       _lines[l]->setSelected(true, minColumn);
516   }
517   if(newstart > _selectionStart) {
518     for(int l = _selectionStart; l < newstart; l++)
519       _lines[l]->setSelected(false);
520   }
521   if(newend > _selectionEnd) {
522     for(int l = _selectionEnd+1; l <= newend; l++)
523       _lines[l]->setSelected(true, minColumn);
524   }
525   if(newend < _selectionEnd) {
526     for(int l = newend+1; l <= _selectionEnd; l++)
527       _lines[l]->setSelected(false);
528   }
529
530   _selectionStart = newstart;
531   _selectionEnd = newend;
532
533   if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
534     if(!_selectingItem) {
535       // _selectingItem has been removed already
536       return;
537     }
538     _lines[curRow]->setSelected(false);
539     _isSelecting = false;
540     _selectionStart = -1;
541     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
542   }
543 }
544
545 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
546   ChatItem *chatItem = chatItemAt(pos);
547   if(!chatItem)
548     return false;
549   if(hasGlobalSelection()) {
550     int row = chatItem->row();
551     if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
552       return true;
553   } else {
554     return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
555   }
556   return false;
557 }
558
559 bool ChatScene::isScrollingAllowed() const {
560   if(_isSelecting)
561     return false;
562
563   // TODO: Handle clicks and single-item selections too
564
565   return true;
566 }
567
568 /******** MOUSE HANDLING **************************************************************************/
569
570 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
571   if(event->buttons() == Qt::LeftButton) {
572     if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
573       if(_clickTimer.isActive()) _clickTimer.stop();
574       if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
575         initiateDrag(event->widget());
576       else {
577         _clickMode = DragStartClick;
578         handleClick(Qt::LeftButton, _clickPos);
579       }
580       _clickMode = NoClick;
581     }
582     if(_isSelecting) {
583       updateSelection(event->scenePos());
584       emit mouseMoveWhileSelecting(event->scenePos());
585       event->accept();
586     } else if(_clickHandled)
587       QGraphicsScene::mouseMoveEvent(event);
588   } else
589     QGraphicsScene::mouseMoveEvent(event);
590 }
591
592 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
593   if(event->buttons() == Qt::LeftButton) {
594     _leftButtonPressed = true;
595     _clickHandled = false;
596     if(!isPosOverSelection(event->scenePos())) {
597       // immediately clear selection if clicked outside; otherwise, wait for potential drag
598       clearSelection();
599     }
600     if(_clickMode != NoClick && _clickTimer.isActive()) {
601       _clickMode = (ClickMode)(_clickMode == TripleClick ? DoubleClick : _clickMode + 1);
602       handleClick(Qt::LeftButton, event->scenePos());
603     } else {
604       _clickMode = SingleClick;
605       _clickPos = event->scenePos();
606     }
607     _clickTimer.start();
608   } else if(event->buttons() == Qt::RightButton) {
609     handleClick(Qt::RightButton, event->scenePos());
610   }
611   if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
612     QGraphicsScene::mouseDoubleClickEvent(event);
613   else
614     QGraphicsScene::mousePressEvent(event);
615 }
616
617 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
618   // we check for doubleclick ourselves, so just call press handler
619   mousePressEvent(event);
620 }
621
622 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
623   if(!event->buttons() & Qt::LeftButton) {
624     _leftButtonPressed = false;
625     if(_clickMode != NoClick) {
626       clearSelection();
627       event->accept();
628       if(!_clickTimer.isActive())
629         handleClick(Qt::LeftButton, _clickPos);
630     } else {
631       // no click -> drag or selection move
632       if(isGloballySelecting()) {
633         putToClipboard(selection());
634         _isSelecting = false;
635         event->accept();
636         return;
637       }
638     }
639   }
640   QGraphicsScene::mouseReleaseEvent(event);
641 }
642
643 void ChatScene::clickTimeout() {
644   if(!_leftButtonPressed && _clickMode == SingleClick)
645     handleClick(Qt::LeftButton, _clickPos);
646 }
647
648 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
649   if(button == Qt::LeftButton) {
650     clearSelection();
651
652     // Now send click down to items
653     ChatItem *chatItem = chatItemAt(scenePos);
654     if(chatItem) {
655       chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
656     }
657     _clickHandled = true;
658   } else if(button == Qt::RightButton) {
659     // TODO: context menu
660
661   }
662 }
663
664 void ChatScene::initiateDrag(QWidget *source) {
665   QDrag *drag = new QDrag(source);
666   QMimeData *mimeData = new QMimeData;
667   mimeData->setText(selection());
668   drag->setMimeData(mimeData);
669
670   drag->exec(Qt::CopyAction);
671 }
672
673 /******** SELECTIONS ******************************************************************************/
674
675 void ChatScene::putToClipboard(const QString &selection) {
676   // TODO Configure clipboards
677 #   ifdef Q_WS_X11
678   QApplication::clipboard()->setText(selection, QClipboard::Selection);
679 #   endif
680 //# else
681   QApplication::clipboard()->setText(selection);
682 //# endif
683 }
684
685 //!\brief Convert current selection to human-readable string.
686 QString ChatScene::selection() const {
687   //TODO Make selection format configurable!
688   if(hasGlobalSelection()) {
689     int start = qMin(_selectionStart, _selectionEnd);
690     int end = qMax(_selectionStart, _selectionEnd);
691     if(start < 0 || end >= _lines.count()) {
692       qDebug() << "Invalid selection range:" << start << end;
693       return QString();
694     }
695     QString result;
696     for(int l = start; l <= end; l++) {
697       if(_selectionMinCol == ChatLineModel::TimestampColumn)
698         result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
699       if(_selectionMinCol <= ChatLineModel::SenderColumn)
700         result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
701       result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
702     }
703     return result;
704   } else if(selectingItem())
705     return selectingItem()->selection();
706   return QString();
707 }
708
709 void ChatScene::clearGlobalSelection() {
710   if(hasGlobalSelection()) {
711     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
712       _lines[l]->setSelected(false);
713     _isSelecting = false;
714     _selectionStart = -1;
715   }
716 }
717
718 void ChatScene::clearSelection() {
719   clearGlobalSelection();
720   if(selectingItem())
721     selectingItem()->clearSelection();
722 }
723
724 /******** *************************************************************************************/
725
726 void ChatScene::requestBacklog() {
727   MessageFilter *filter = qobject_cast<MessageFilter*>(model());
728   if(filter)
729     return filter->requestBacklog();
730   return;
731 }
732
733 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) {
734   if(x < _firstColHandle->x())
735     return ChatLineModel::TimestampColumn;
736   if(x < _secondColHandle->x())
737     return ChatLineModel::SenderColumn;
738
739   return ChatLineModel::ContentsColumn;
740 }
741
742 int ChatScene::rowByScenePos(qreal y) {
743   // This is somewhat hacky... we look at the contents item that is at the given y position, since
744   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
745   // ChatItems cover their ChatLine, so we won't get to the latter directly.
746   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, y)));
747   if(!contentItem) return -1;
748   return contentItem->row();
749 }
750
751 void ChatScene::updateSceneRect(qreal width) {
752   if(_lines.isEmpty()) {
753     updateSceneRect(QRectF(0, 0, width, 0));
754     return;
755   }
756
757   // we hide day change messages at the top by making the scene rect smaller
758   // and by calling QGraphicsItem::hide() on all leading day change messages
759   // the first one is needed to ensure proper scrollbar ranges
760   // the second for cases where the viewport is larger then the set scenerect
761   //  (in this case the items are shown anyways)
762   if(_firstLineRow == -1) {
763     int numRows = model()->rowCount();
764     _firstLineRow = 0;
765     QModelIndex firstLineIdx;
766     while(_firstLineRow < numRows) {
767       firstLineIdx = model()->index(_firstLineRow, 0);
768       if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
769         break;
770       _lines.at(_firstLineRow)->hide();
771       _firstLineRow++;
772     }
773   }
774
775   // the following call should be safe. If it crashes something went wrong during insert/remove
776   if(_firstLineRow < _lines.count()) {
777     ChatLine *firstLine = _lines.at(_firstLineRow);
778     ChatLine *lastLine = _lines.last();
779     updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
780   } else {
781     // empty scene rect
782     updateSceneRect(QRectF(0, 0, width, 0));
783   }
784 }
785
786 void ChatScene::updateSceneRect(const QRectF &rect) {
787   _sceneRect = rect;
788   setSceneRect(rect);
789   update();
790 }
791
792 bool ChatScene::event(QEvent *e) {
793   if(e->type() == QEvent::ApplicationPaletteChange) {
794     _firstColHandle->setColor(QApplication::palette().windowText().color());
795     _secondColHandle->setColor(QApplication::palette().windowText().color());
796   }
797   return QGraphicsScene::event(e);
798 }
799
800 /******** WEB PREVIEW *****************************************************************************/
801
802 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
803 #ifndef HAVE_WEBKIT
804   Q_UNUSED(parentItem)
805   Q_UNUSED(url)
806   Q_UNUSED(urlRect)
807 #else
808   if(!_showWebPreview)
809     return;
810
811   if(webPreview.parentItem != parentItem)
812     webPreview.parentItem = parentItem;
813
814   if(webPreview.url != url) {
815     webPreview.url = url;
816     // load a new web view and delete the old one (if exists)
817     if(webPreview.previewItem && webPreview.previewItem->scene()) {
818       removeItem(webPreview.previewItem);
819       delete webPreview.previewItem;
820     }
821     webPreview.previewItem = new WebPreviewItem(url);
822     webPreview.delayTimer.start(2000);
823     webPreview.deleteTimer.stop();
824   } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
825       // we just have to readd the item to the scene
826       webPreview.delayTimer.start(2000);
827       webPreview.deleteTimer.stop();
828   }
829   if(webPreview.urlRect != urlRect) {
830     webPreview.urlRect = urlRect;
831     qreal previewY = urlRect.bottom();
832     qreal previewX = urlRect.x();
833     if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
834       previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
835
836     if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
837       previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
838
839     webPreview.previewItem->setPos(previewX, previewY);
840   }
841 #endif
842 }
843
844 void ChatScene::showWebPreviewEvent() {
845 #ifdef HAVE_WEBKIT
846   if(webPreview.previewItem)
847     addItem(webPreview.previewItem);
848 #endif
849 }
850
851 void ChatScene::clearWebPreview(ChatItem *parentItem) {
852 #ifndef HAVE_WEBKIT
853   Q_UNUSED(parentItem)
854 #else
855   if(parentItem == 0 || webPreview.parentItem == parentItem) {
856     if(webPreview.previewItem && webPreview.previewItem->scene()) {
857       removeItem(webPreview.previewItem);
858       webPreview.deleteTimer.start();
859     }
860     webPreview.delayTimer.stop();
861   }
862 #endif
863 }
864
865 void ChatScene::deleteWebPreviewEvent() {
866 #ifdef HAVE_WEBKIT
867   if(webPreview.previewItem) {
868     delete webPreview.previewItem;
869     webPreview.previewItem = 0;
870   }
871   webPreview.parentItem = 0;
872   webPreview.url = QString();
873   webPreview.urlRect = QRectF();
874 #endif
875 }
876
877 void ChatScene::showWebPreviewChanged() {
878   ChatViewSettings settings;
879   _showWebPreview = settings.showWebPreview();
880 }