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