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