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