1 /***************************************************************************
2 * Copyright (C) 2005-08 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include <QApplication>
23 #include <QGraphicsSceneMouseEvent>
24 #include <QPersistentModelIndex>
29 #include "chatlinemodelitem.h"
30 #include "chatscene.h"
32 #include "clientbacklogmanager.h"
33 #include "columnhandleitem.h"
34 #include "messagefilter.h"
36 #include "qtuistyle.h"
37 #include "chatviewsettings.h"
38 #include "webpreviewitem.h"
40 const qreal minContentsWidth = 200;
42 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
43 : QGraphicsScene(0, 0, width, 0, parent),
46 _singleBufferScene(false),
47 _sceneRect(0, 0, width, 0),
50 _cutoffMode(CutoffRight),
55 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
57 _singleBufferScene = filter->isSingleBufferFilter();
60 ChatViewSettings defaultSettings;
61 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
62 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
64 ChatViewSettings viewSettings(this);
65 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
66 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
68 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
69 addItem(_firstColHandle);
70 _firstColHandle->setXPos(_firstColHandlePos);
71 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
72 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
74 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
75 addItem(_secondColHandle);
76 _secondColHandle->setXPos(_secondColHandlePos);
77 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
79 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
83 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
84 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
85 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
86 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
88 if(model->rowCount() > 0)
89 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
92 webPreview.delayTimer.setSingleShot(true);
93 connect(&webPreview.delayTimer, SIGNAL(timeout()), this, SLOT(showWebPreviewEvent()));
94 webPreview.deleteTimer.setInterval(600000);
95 connect(&webPreview.deleteTimer, SIGNAL(timeout()), this, SLOT(deleteWebPreviewEvent()));
98 setItemIndexMethod(QGraphicsScene::NoIndex);
101 ChatScene::~ChatScene() {
104 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
106 // QModelIndex sidx = model()->index(start, 0);
107 // QModelIndex eidx = model()->index(end, 0);
108 // qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
112 qreal width = _sceneRect.width();
113 bool atBottom = (start == _lines.count());
114 bool atTop = !atBottom && (start == 0);
115 bool moveTop = false;
117 if(start < _lines.count()) {
118 y = _lines.value(start)->y();
119 } else if(atBottom && !_lines.isEmpty()) {
120 y = _lines.last()->y() + _lines.last()->height();
123 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
124 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
125 qreal timestampWidth = firstColumnHandle()->sceneLeft();
126 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
127 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
130 for(int i = end; i >= start; i--) {
131 ChatLine *line = new ChatLine(i, model(),
133 timestampWidth, senderWidth, contentsWidth,
134 senderPos, contentsPos);
136 line->setPos(0, y-h);
137 _lines.insert(start, line);
141 for(int i = start; i <= end; i++) {
142 ChatLine *line = new ChatLine(i, model(),
144 timestampWidth, senderWidth, contentsWidth,
145 senderPos, contentsPos);
146 line->setPos(0, y+h);
148 _lines.insert(i, line);
153 // update existing items
154 for(int i = end+1; i < _lines.count(); i++) {
155 _lines[i]->setRow(i);
159 if(_selectionStart >= 0) {
160 int offset = end - start + 1;
161 if(_selectionStart >= start) _selectionStart += offset;
162 if(_selectionEnd >= start) _selectionEnd += offset;
163 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
164 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
167 // neither pre- or append means we have to do dirty work: move items...
169 int moveEnd = _lines.count() - 1;
171 if(!(atTop || atBottom)) {
172 // move top means: moving 0 to end (aka: end + 1)
173 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
174 if(end + 1 < _lines.count() - end - 1) {
184 for(int i = moveStart; i <= moveEnd; i++) {
186 line->setPos(0, line->pos().y() + offset);
190 // check if all went right
191 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
193 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
194 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
195 // 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();
196 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
197 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
201 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
202 // if(end + 1 < _lines.count()) {
203 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
204 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
205 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
206 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
207 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
213 if(start < _firstLineRow) {
214 int prevFirstLineRow = _firstLineRow + (end - start + 1);
215 for(int i = end + 1; i < prevFirstLineRow; i++) {
216 _lines.at(i)->show();
219 // force new search for first proper line
223 if(atBottom || (!atTop && !moveTop)) {
224 emit lastLineChanged(_lines.last(), h);
228 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
231 qreal h = 0; // total height of removed items;
233 bool atTop = (start == 0);
234 bool atBottom = (end == _lines.count() - 1);
235 bool moveTop = false;
237 // remove items from scene
238 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
239 int lineCount = start;
240 while(lineIter != _lines.end() && lineCount <= end) {
241 h += (*lineIter)->height();
243 lineIter = _lines.erase(lineIter);
247 // update rows of remaining chatlines
248 for(int i = start; i < _lines.count(); i++) {
249 _lines.at(i)->setRow(i);
253 if(_selectionStart >= 0) {
254 int offset = end - start + 1;
255 if(_selectionStart >= start)
256 _selectionStart -= offset;
257 if(_selectionEnd >= start)
258 _selectionEnd -= offset;
259 if(_firstSelectionRow >= start)
260 _firstSelectionRow -= offset;
261 if(_lastSelectionRow >= start)
262 _lastSelectionRow -= offset;
265 // neither removing at bottom or top means we have to move items...
266 if(!(atTop || atBottom)) {
269 int moveEnd = _lines.count() - 1;
270 if(start < _lines.count() - start) {
280 for(int i = moveStart; i <= moveEnd; i++) {
282 line->setPos(0, line->pos().y() + offset);
286 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
289 // when searching for the first non-date-line we have to take into account that our
290 // model still contains the just removed lines so we cannot simply call updateSceneRect()
291 int numRows = model()->rowCount();
292 QModelIndex firstLineIdx;
294 bool needOffset = false;
297 if(_firstLineRow >= start && _firstLineRow <= end) {
298 _firstLineRow = end + 1;
301 firstLineIdx = model()->index(_firstLineRow, 0);
302 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
305 _firstLineRow -= end - start + 1;
309 void ChatScene::updateForViewport(qreal width, qreal height) {
310 _viewportHeight = height;
314 void ChatScene::setWidth(qreal width) {
315 if(width == _sceneRect.width())
318 // clock_t startT = clock();
320 // disabling the index while doing this complex updates is about
321 // 2 to 10 times faster!
322 //setItemIndexMethod(QGraphicsScene::NoIndex);
324 QList<ChatLine *>::iterator lineIter = _lines.end();
325 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
326 qreal linePos = _sceneRect.y() + _sceneRect.height();
327 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
328 while(lineIter != lineIterBegin) {
330 (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
332 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
334 updateSceneRect(width);
337 // clock_t endT = clock();
338 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
341 void ChatScene::firstHandlePositionChanged(qreal xpos) {
342 if(_firstColHandlePos == xpos)
345 _firstColHandlePos = xpos;
346 ChatViewSettings viewSettings(this);
347 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
348 ChatViewSettings defaultSettings;
349 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
351 // clock_t startT = clock();
353 // disabling the index while doing this complex updates is about
354 // 2 to 10 times faster!
355 //setItemIndexMethod(QGraphicsScene::NoIndex);
357 QList<ChatLine *>::iterator lineIter = _lines.end();
358 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
359 qreal timestampWidth = firstColumnHandle()->sceneLeft();
360 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
361 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
363 while(lineIter != lineIterBegin) {
365 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
367 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
371 // clock_t endT = clock();
372 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
375 void ChatScene::secondHandlePositionChanged(qreal xpos) {
376 if(_secondColHandlePos == xpos)
379 _secondColHandlePos = xpos;
380 ChatViewSettings viewSettings(this);
381 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
382 ChatViewSettings defaultSettings;
383 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
385 // clock_t startT = clock();
387 // disabling the index while doing this complex updates is about
388 // 2 to 10 times faster!
389 //setItemIndexMethod(QGraphicsScene::NoIndex);
391 QList<ChatLine *>::iterator lineIter = _lines.end();
392 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
393 qreal linePos = _sceneRect.y() + _sceneRect.height();
394 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
395 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
396 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
397 while(lineIter != lineIterBegin) {
399 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
401 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
405 // clock_t endT = clock();
406 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
409 void ChatScene::setHandleXLimits() {
410 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
411 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
414 void ChatScene::setSelectingItem(ChatItem *item) {
415 if(_selectingItem) _selectingItem->clearSelection();
416 _selectingItem = item;
419 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
420 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
421 _selectionStartCol = _selectionMinCol = item->column();
423 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
424 updateSelection(item->mapToScene(itemPos));
427 void ChatScene::updateSelection(const QPointF &pos) {
428 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
429 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
430 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, pos.y())));
431 if(!contentItem) return;
433 int curRow = contentItem->row();
435 if(pos.x() > _secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
436 else if(pos.x() > _firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
437 else curColumn = ChatLineModel::TimestampColumn;
439 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
440 if(minColumn != _selectionMinCol) {
441 _selectionMinCol = minColumn;
442 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
443 _lines[l]->setSelected(true, minColumn);
446 int newstart = qMin(curRow, _firstSelectionRow);
447 int newend = qMax(curRow, _firstSelectionRow);
448 if(newstart < _selectionStart) {
449 for(int l = newstart; l < _selectionStart; l++)
450 _lines[l]->setSelected(true, minColumn);
452 if(newstart > _selectionStart) {
453 for(int l = _selectionStart; l < newstart; l++)
454 _lines[l]->setSelected(false);
456 if(newend > _selectionEnd) {
457 for(int l = _selectionEnd+1; l <= newend; l++)
458 _lines[l]->setSelected(true, minColumn);
460 if(newend < _selectionEnd) {
461 for(int l = newend+1; l <= _selectionEnd; l++)
462 _lines[l]->setSelected(false);
465 _selectionStart = newstart;
466 _selectionEnd = newend;
467 _lastSelectionRow = curRow;
469 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
470 if(!_selectingItem) {
471 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
474 _lines[curRow]->setSelected(false);
475 _isSelecting = false;
476 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
480 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
481 if(_isSelecting && event->buttons() == Qt::LeftButton) {
482 updateSelection(event->scenePos());
485 QGraphicsScene::mouseMoveEvent(event);
489 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
490 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
491 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
492 _lines[l]->setSelected(false);
494 _selectionStart = -1;
495 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
497 QGraphicsScene::mousePressEvent(event);
501 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
502 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
503 putToClipboard(selectionToString());
504 _isSelecting = false;
507 QGraphicsScene::mouseReleaseEvent(event);
511 void ChatScene::putToClipboard(const QString &selection) {
512 // TODO Configure clipboards
514 QApplication::clipboard()->setText(selection, QClipboard::Selection);
517 QApplication::clipboard()->setText(selection);
521 //!\brief Convert current selection to human-readable string.
522 QString ChatScene::selectionToString() const {
523 //TODO Make selection format configurable!
524 if(!_isSelecting) return QString();
525 int start = qMin(_selectionStart, _selectionEnd);
526 int end = qMax(_selectionStart, _selectionEnd);
527 if(start < 0 || end >= _lines.count()) {
528 qDebug() << "Invalid selection range:" << start << end;
532 for(int l = start; l <= end; l++) {
533 if(_selectionMinCol == ChatLineModel::TimestampColumn)
534 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
535 if(_selectionMinCol <= ChatLineModel::SenderColumn)
536 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
537 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
542 void ChatScene::requestBacklog() {
543 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
545 return filter->requestBacklog();
549 int ChatScene::sectionByScenePos(int x) {
550 if(x < _firstColHandle->x())
551 return ChatLineModel::TimestampColumn;
552 if(x < _secondColHandle->x())
553 return ChatLineModel::SenderColumn;
555 return ChatLineModel::ContentsColumn;
558 void ChatScene::updateSceneRect(qreal width) {
559 if(_lines.isEmpty()) {
560 updateSceneRect(QRectF(0, 0, width, 0));
564 // we hide day change messages at the top by making the scene rect smaller
565 // and by calling QGraphicsItem::hide() on all leading day change messages
566 // the first one is needed to ensure proper scrollbar ranges
567 // the second for cases where the viewport is larger then the set scenerect
568 // (in this case the items are shown anyways)
569 if(_firstLineRow == -1) {
570 int numRows = model()->rowCount();
572 QModelIndex firstLineIdx;
573 while(_firstLineRow < numRows) {
574 firstLineIdx = model()->index(_firstLineRow, 0);
575 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
577 _lines.at(_firstLineRow)->hide();
582 // the following call should be safe. If it crashes something went wrong during insert/remove
583 if(_firstLineRow < _lines.count()) {
584 ChatLine *firstLine = _lines.at(_firstLineRow);
585 ChatLine *lastLine = _lines.last();
586 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
589 updateSceneRect(QRectF(0, 0, width, 0));
593 void ChatScene::updateSceneRect(const QRectF &rect) {
599 bool ChatScene::event(QEvent *e) {
600 if(e->type() == QEvent::ApplicationPaletteChange) {
601 _firstColHandle->setColor(QApplication::palette().windowText().color());
602 _secondColHandle->setColor(QApplication::palette().windowText().color());
604 return QGraphicsScene::event(e);
607 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
613 if(webPreview.parentItem != parentItem)
614 webPreview.parentItem = parentItem;
616 if(webPreview.url != url) {
617 webPreview.url = url;
618 // load a new web view and delete the old one (if exists)
619 if(webPreview.previewItem && webPreview.previewItem->scene()) {
620 removeItem(webPreview.previewItem);
621 delete webPreview.previewItem;
623 webPreview.previewItem = new WebPreviewItem(url);
624 webPreview.delayTimer.start(2000);
625 webPreview.deleteTimer.stop();
626 } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
627 // we just have to readd the item to the scene
628 webPreview.delayTimer.start(2000);
629 webPreview.deleteTimer.stop();
631 if(webPreview.urlRect != urlRect) {
632 webPreview.urlRect = urlRect;
633 qreal previewY = urlRect.bottom();
634 qreal previewX = urlRect.x();
635 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
636 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
638 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
639 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
641 webPreview.previewItem->setPos(previewX, previewY);
646 void ChatScene::showWebPreviewEvent() {
648 if(webPreview.previewItem)
649 addItem(webPreview.previewItem);
653 void ChatScene::clearWebPreview(ChatItem *parentItem) {
657 if(parentItem == 0 || webPreview.parentItem == parentItem) {
658 if(webPreview.previewItem && webPreview.previewItem->scene()) {
659 removeItem(webPreview.previewItem);
660 webPreview.deleteTimer.start();
662 webPreview.delayTimer.stop();
667 void ChatScene::deleteWebPreviewEvent() {
669 if(webPreview.previewItem) {
670 delete webPreview.previewItem;
671 webPreview.previewItem = 0;
673 webPreview.parentItem = 0;
674 webPreview.url = QString();
675 webPreview.urlRect = QRectF();