Revamping ChatView/ChatScene's mouse handling
[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         handleClick(Qt::LeftButton, _clickPos);
578       _clickMode = NoClick;
579     }
580     if(_isSelecting) {
581       updateSelection(event->scenePos());
582       emit mouseMoveWhileSelecting(event->scenePos());
583       event->accept();
584     } else if(_clickHandled)
585       QGraphicsScene::mouseMoveEvent(event);
586   } else
587     QGraphicsScene::mouseMoveEvent(event);
588 }
589
590 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
591   if(event->buttons() == Qt::LeftButton) {
592     _leftButtonPressed = true;
593     _clickHandled = false;
594     if(!isPosOverSelection(event->scenePos())) {
595       // immediately clear selection if clicked outside; otherwise, wait for potential drag
596       clearSelection();
597     }
598     if(_clickMode != NoClick && _clickTimer.isActive()) {
599       _clickMode = (ClickMode)(_clickMode == TripleClick ? DoubleClick : _clickMode + 1);
600       handleClick(Qt::LeftButton, event->scenePos());
601     } else {
602       _clickMode = SingleClick;
603       _clickPos = event->scenePos();
604     }
605     _clickTimer.start();
606   } else if(event->buttons() == Qt::RightButton) {
607     handleClick(Qt::RightButton, event->scenePos());
608   }
609   if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
610     QGraphicsScene::mouseDoubleClickEvent(event);
611   else
612     QGraphicsScene::mousePressEvent(event);
613 }
614
615 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
616   // we check for doubleclick ourselves, so just call press handler
617   mousePressEvent(event);
618 }
619
620 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
621   if(!event->buttons() & Qt::LeftButton) {
622     _leftButtonPressed = false;
623     if(_clickMode != NoClick) {
624       clearSelection();
625       event->accept();
626       if(!_clickTimer.isActive())
627         handleClick(Qt::LeftButton, _clickPos);
628     } else {
629       // no click -> drag or selection move
630       if(isGloballySelecting()) {
631         putToClipboard(selection());
632         _isSelecting = false;
633         event->accept();
634         return;
635       }
636     }
637   }
638   QGraphicsScene::mouseReleaseEvent(event);
639 }
640
641 void ChatScene::clickTimeout() {
642   if(!_leftButtonPressed && _clickMode == SingleClick)
643     handleClick(Qt::LeftButton, _clickPos);
644 }
645
646 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
647   if(button == Qt::LeftButton) {
648     clearSelection();
649
650     // Now send click down to items
651     ChatItem *chatItem = chatItemAt(scenePos);
652     if(chatItem) {
653       chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
654     }
655     _clickHandled = true;
656   } else if(button == Qt::RightButton) {
657     // TODO: context menu
658
659   }
660 }
661
662 void ChatScene::initiateDrag(QWidget *source) {
663   QDrag *drag = new QDrag(source);
664   QMimeData *mimeData = new QMimeData;
665   mimeData->setText(selection());
666   drag->setMimeData(mimeData);
667
668   drag->exec(Qt::CopyAction);
669 }
670
671 /******** SELECTIONS ******************************************************************************/
672
673 void ChatScene::putToClipboard(const QString &selection) {
674   // TODO Configure clipboards
675 #   ifdef Q_WS_X11
676   QApplication::clipboard()->setText(selection, QClipboard::Selection);
677 #   endif
678 //# else
679   QApplication::clipboard()->setText(selection);
680 //# endif
681 }
682
683 //!\brief Convert current selection to human-readable string.
684 QString ChatScene::selection() const {
685   //TODO Make selection format configurable!
686   if(hasGlobalSelection()) {
687     int start = qMin(_selectionStart, _selectionEnd);
688     int end = qMax(_selectionStart, _selectionEnd);
689     if(start < 0 || end >= _lines.count()) {
690       qDebug() << "Invalid selection range:" << start << end;
691       return QString();
692     }
693     QString result;
694     for(int l = start; l <= end; l++) {
695       if(_selectionMinCol == ChatLineModel::TimestampColumn)
696         result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
697       if(_selectionMinCol <= ChatLineModel::SenderColumn)
698         result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
699       result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
700     }
701     return result;
702   } else if(selectingItem())
703     return selectingItem()->selection();
704   return QString();
705 }
706
707 void ChatScene::clearGlobalSelection() {
708   if(hasGlobalSelection()) {
709     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
710       _lines[l]->setSelected(false);
711     _isSelecting = false;
712     _selectionStart = -1;
713   }
714 }
715
716 void ChatScene::clearSelection() {
717   clearGlobalSelection();
718   if(selectingItem())
719     selectingItem()->clearSelection();
720 }
721
722 /******** *************************************************************************************/
723
724 void ChatScene::requestBacklog() {
725   MessageFilter *filter = qobject_cast<MessageFilter*>(model());
726   if(filter)
727     return filter->requestBacklog();
728   return;
729 }
730
731 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) {
732   if(x < _firstColHandle->x())
733     return ChatLineModel::TimestampColumn;
734   if(x < _secondColHandle->x())
735     return ChatLineModel::SenderColumn;
736
737   return ChatLineModel::ContentsColumn;
738 }
739
740 int ChatScene::rowByScenePos(qreal y) {
741   // This is somewhat hacky... we look at the contents item that is at the given y position, since
742   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
743   // ChatItems cover their ChatLine, so we won't get to the latter directly.
744   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, y)));
745   if(!contentItem) return -1;
746   return contentItem->row();
747 }
748
749 void ChatScene::updateSceneRect(qreal width) {
750   if(_lines.isEmpty()) {
751     updateSceneRect(QRectF(0, 0, width, 0));
752     return;
753   }
754
755   // we hide day change messages at the top by making the scene rect smaller
756   // and by calling QGraphicsItem::hide() on all leading day change messages
757   // the first one is needed to ensure proper scrollbar ranges
758   // the second for cases where the viewport is larger then the set scenerect
759   //  (in this case the items are shown anyways)
760   if(_firstLineRow == -1) {
761     int numRows = model()->rowCount();
762     _firstLineRow = 0;
763     QModelIndex firstLineIdx;
764     while(_firstLineRow < numRows) {
765       firstLineIdx = model()->index(_firstLineRow, 0);
766       if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
767         break;
768       _lines.at(_firstLineRow)->hide();
769       _firstLineRow++;
770     }
771   }
772
773   // the following call should be safe. If it crashes something went wrong during insert/remove
774   if(_firstLineRow < _lines.count()) {
775     ChatLine *firstLine = _lines.at(_firstLineRow);
776     ChatLine *lastLine = _lines.last();
777     updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
778   } else {
779     // empty scene rect
780     updateSceneRect(QRectF(0, 0, width, 0));
781   }
782 }
783
784 void ChatScene::updateSceneRect(const QRectF &rect) {
785   _sceneRect = rect;
786   setSceneRect(rect);
787   update();
788 }
789
790 bool ChatScene::event(QEvent *e) {
791   if(e->type() == QEvent::ApplicationPaletteChange) {
792     _firstColHandle->setColor(QApplication::palette().windowText().color());
793     _secondColHandle->setColor(QApplication::palette().windowText().color());
794   }
795   return QGraphicsScene::event(e);
796 }
797
798 /******** WEB PREVIEW *****************************************************************************/
799
800 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
801 #ifndef HAVE_WEBKIT
802   Q_UNUSED(parentItem)
803   Q_UNUSED(url)
804   Q_UNUSED(urlRect)
805 #else
806   if(!_showWebPreview)
807     return;
808
809   if(webPreview.parentItem != parentItem)
810     webPreview.parentItem = parentItem;
811
812   if(webPreview.url != url) {
813     webPreview.url = url;
814     // load a new web view and delete the old one (if exists)
815     if(webPreview.previewItem && webPreview.previewItem->scene()) {
816       removeItem(webPreview.previewItem);
817       delete webPreview.previewItem;
818     }
819     webPreview.previewItem = new WebPreviewItem(url);
820     webPreview.delayTimer.start(2000);
821     webPreview.deleteTimer.stop();
822   } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
823       // we just have to readd the item to the scene
824       webPreview.delayTimer.start(2000);
825       webPreview.deleteTimer.stop();
826   }
827   if(webPreview.urlRect != urlRect) {
828     webPreview.urlRect = urlRect;
829     qreal previewY = urlRect.bottom();
830     qreal previewX = urlRect.x();
831     if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
832       previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
833
834     if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
835       previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
836
837     webPreview.previewItem->setPos(previewX, previewY);
838   }
839 #endif
840 }
841
842 void ChatScene::showWebPreviewEvent() {
843 #ifdef HAVE_WEBKIT
844   if(webPreview.previewItem)
845     addItem(webPreview.previewItem);
846 #endif
847 }
848
849 void ChatScene::clearWebPreview(ChatItem *parentItem) {
850 #ifndef HAVE_WEBKIT
851   Q_UNUSED(parentItem)
852 #else
853   if(parentItem == 0 || webPreview.parentItem == parentItem) {
854     if(webPreview.previewItem && webPreview.previewItem->scene()) {
855       removeItem(webPreview.previewItem);
856       webPreview.deleteTimer.start();
857     }
858     webPreview.delayTimer.stop();
859   }
860 #endif
861 }
862
863 void ChatScene::deleteWebPreviewEvent() {
864 #ifdef HAVE_WEBKIT
865   if(webPreview.previewItem) {
866     delete webPreview.previewItem;
867     webPreview.previewItem = 0;
868   }
869   webPreview.parentItem = 0;
870   webPreview.url = QString();
871   webPreview.urlRect = QRectF();
872 #endif
873 }
874
875 void ChatScene::showWebPreviewChanged() {
876   ChatViewSettings settings;
877   _showWebPreview = settings.showWebPreview();
878 }