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