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