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