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