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