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