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