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