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