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