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>();
111 qreal y = _sceneRect.y();
112 qreal width = _sceneRect.width();
114 bool atBottom = false;
115 bool moveTop = false;
117 if(start > 0 && start < _lines.count()) {
118 y = _lines.value(start)->y();
121 if(start == _lines.count()) {
122 y = _sceneRect.bottom();
127 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
128 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
129 qreal timestampWidth = firstColumnHandle()->sceneLeft();
130 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
131 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
134 for(int i = end; i >= start; i--) {
135 ChatLine *line = new ChatLine(i, model(),
137 timestampWidth, senderWidth, contentsWidth,
138 senderPos, contentsPos);
140 line->setPos(0, y-h);
141 _lines.insert(start, line);
145 for(int i = start; i <= end; i++) {
146 ChatLine *line = new ChatLine(i, model(),
148 timestampWidth, senderWidth, contentsWidth,
149 senderPos, contentsPos);
150 line->setPos(0, y+h);
152 _lines.insert(i, line);
157 // update existing items
158 for(int i = end+1; i < _lines.count(); i++) {
159 _lines[i]->setRow(i);
163 if(_selectionStart >= 0) {
164 int offset = end - start + 1;
165 if(_selectionStart >= start) _selectionStart += offset;
166 if(_selectionEnd >= start) _selectionEnd += offset;
167 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
168 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
171 // neither pre- or append means we have to do dirty work: move items...
172 if(!(atTop || atBottom)) {
175 int moveEnd = _lines.count() - 1;
176 // move top means: moving 0 to end (aka: end + 1)
177 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
178 if(end + 1 < _lines.count() - end - 1) {
188 for(int i = moveStart; i <= moveEnd; i++) {
190 line->setPos(0, line->pos().y() + offset);
194 // check if all went right
195 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
196 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
199 if(start < _firstLineRow) {
200 int prevFirstLineRow = _firstLineRow + (end - start + 1);
201 for(int i = end + 1; i < prevFirstLineRow; i++) {
202 _lines.at(i)->show();
205 // force new search for first proper line
209 if(atBottom || (!atTop && !moveTop)) {
210 emit lastLineChanged(_lines.last(), h);
214 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
217 qreal h = 0; // total height of removed items;
219 bool atTop = (start == 0);
220 bool atBottom = (end == _lines.count() - 1);
221 bool moveTop = false;
223 // remove items from scene
224 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
225 int lineCount = start;
226 while(lineIter != _lines.end() && lineCount <= end) {
227 h += (*lineIter)->height();
229 lineIter = _lines.erase(lineIter);
233 // update rows of remaining chatlines
234 for(int i = start; i < _lines.count(); i++) {
235 _lines.at(i)->setRow(i);
239 if(_selectionStart >= 0) {
240 int offset = end - start + 1;
241 if(_selectionStart >= start)
242 _selectionStart -= offset;
243 if(_selectionEnd >= start)
244 _selectionEnd -= offset;
245 if(_firstSelectionRow >= start)
246 _firstSelectionRow -= offset;
247 if(_lastSelectionRow >= start)
248 _lastSelectionRow -= offset;
251 // neither removing at bottom or top means we have to move items...
252 if(!(atTop || atBottom)) {
255 int moveEnd = _lines.count() - 1;
256 if(start < _lines.count() - start) {
266 for(int i = moveStart; i <= moveEnd; i++) {
268 line->setPos(0, line->pos().y() + offset);
272 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
275 // when searching for the first non-date-line we have to take into account that our
276 // model still contains the just removed lines so we cannot simply call updateSceneRect()
277 int numRows = model()->rowCount();
278 QModelIndex firstLineIdx;
280 bool needOffset = false;
283 if(_firstLineRow >= start && _firstLineRow <= end) {
284 _firstLineRow = end + 1;
287 firstLineIdx = model()->index(_firstLineRow, 0);
288 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
291 _firstLineRow -= end - start + 1;
295 void ChatScene::updateForViewport(qreal width, qreal height) {
296 _viewportHeight = height;
300 void ChatScene::setWidth(qreal width) {
301 if(width == _sceneRect.width())
304 // clock_t startT = clock();
306 // disabling the index while doing this complex updates is about
307 // 2 to 10 times faster!
308 //setItemIndexMethod(QGraphicsScene::NoIndex);
310 QList<ChatLine *>::iterator lineIter = _lines.end();
311 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
312 qreal linePos = _sceneRect.y() + _sceneRect.height();
313 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
314 while(lineIter != lineIterBegin) {
316 (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
318 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
320 updateSceneRect(width);
323 // clock_t endT = clock();
324 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
327 void ChatScene::firstHandlePositionChanged(qreal xpos) {
328 if(_firstColHandlePos == xpos)
331 _firstColHandlePos = xpos;
332 ChatViewSettings viewSettings(this);
333 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
334 ChatViewSettings defaultSettings;
335 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
337 // clock_t startT = clock();
339 // disabling the index while doing this complex updates is about
340 // 2 to 10 times faster!
341 //setItemIndexMethod(QGraphicsScene::NoIndex);
343 QList<ChatLine *>::iterator lineIter = _lines.end();
344 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
345 qreal timestampWidth = firstColumnHandle()->sceneLeft();
346 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
347 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
349 while(lineIter != lineIterBegin) {
351 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
353 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
357 // clock_t endT = clock();
358 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
361 void ChatScene::secondHandlePositionChanged(qreal xpos) {
362 if(_secondColHandlePos == xpos)
365 _secondColHandlePos = xpos;
366 ChatViewSettings viewSettings(this);
367 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
368 ChatViewSettings defaultSettings;
369 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
371 // clock_t startT = clock();
373 // disabling the index while doing this complex updates is about
374 // 2 to 10 times faster!
375 //setItemIndexMethod(QGraphicsScene::NoIndex);
377 QList<ChatLine *>::iterator lineIter = _lines.end();
378 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
379 qreal linePos = _sceneRect.y() + _sceneRect.height();
380 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
381 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
382 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
383 while(lineIter != lineIterBegin) {
385 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
387 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
391 // clock_t endT = clock();
392 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
395 void ChatScene::setHandleXLimits() {
396 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
397 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
400 void ChatScene::setSelectingItem(ChatItem *item) {
401 if(_selectingItem) _selectingItem->clearSelection();
402 _selectingItem = item;
405 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
406 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
407 _selectionStartCol = _selectionMinCol = item->column();
409 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
410 updateSelection(item->mapToScene(itemPos));
413 void ChatScene::updateSelection(const QPointF &pos) {
414 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
415 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
416 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, pos.y())));
417 if(!contentItem) return;
419 int curRow = contentItem->row();
421 if(pos.x() > _secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
422 else if(pos.x() > _firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
423 else curColumn = ChatLineModel::TimestampColumn;
425 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
426 if(minColumn != _selectionMinCol) {
427 _selectionMinCol = minColumn;
428 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
429 _lines[l]->setSelected(true, minColumn);
432 int newstart = qMin(curRow, _firstSelectionRow);
433 int newend = qMax(curRow, _firstSelectionRow);
434 if(newstart < _selectionStart) {
435 for(int l = newstart; l < _selectionStart; l++)
436 _lines[l]->setSelected(true, minColumn);
438 if(newstart > _selectionStart) {
439 for(int l = _selectionStart; l < newstart; l++)
440 _lines[l]->setSelected(false);
442 if(newend > _selectionEnd) {
443 for(int l = _selectionEnd+1; l <= newend; l++)
444 _lines[l]->setSelected(true, minColumn);
446 if(newend < _selectionEnd) {
447 for(int l = newend+1; l <= _selectionEnd; l++)
448 _lines[l]->setSelected(false);
451 _selectionStart = newstart;
452 _selectionEnd = newend;
453 _lastSelectionRow = curRow;
455 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
456 if(!_selectingItem) {
457 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
460 _lines[curRow]->setSelected(false);
461 _isSelecting = false;
462 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
466 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
467 if(_isSelecting && event->buttons() == Qt::LeftButton) {
468 updateSelection(event->scenePos());
471 QGraphicsScene::mouseMoveEvent(event);
475 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
476 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
477 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
478 _lines[l]->setSelected(false);
480 _selectionStart = -1;
481 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
483 QGraphicsScene::mousePressEvent(event);
487 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
488 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
489 putToClipboard(selectionToString());
490 _isSelecting = false;
493 QGraphicsScene::mouseReleaseEvent(event);
497 void ChatScene::putToClipboard(const QString &selection) {
498 // TODO Configure clipboards
500 QApplication::clipboard()->setText(selection, QClipboard::Selection);
503 QApplication::clipboard()->setText(selection);
507 //!\brief Convert current selection to human-readable string.
508 QString ChatScene::selectionToString() const {
509 //TODO Make selection format configurable!
510 if(!_isSelecting) return QString();
511 int start = qMin(_selectionStart, _selectionEnd);
512 int end = qMax(_selectionStart, _selectionEnd);
513 if(start < 0 || end >= _lines.count()) {
514 qDebug() << "Invalid selection range:" << start << end;
518 for(int l = start; l <= end; l++) {
519 if(_selectionMinCol == ChatLineModel::TimestampColumn)
520 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
521 if(_selectionMinCol <= ChatLineModel::SenderColumn)
522 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
523 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
528 void ChatScene::requestBacklog() {
529 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
531 return filter->requestBacklog();
535 int ChatScene::sectionByScenePos(int x) {
536 if(x < _firstColHandle->x())
537 return ChatLineModel::TimestampColumn;
538 if(x < _secondColHandle->x())
539 return ChatLineModel::SenderColumn;
541 return ChatLineModel::ContentsColumn;
544 void ChatScene::updateSceneRect(qreal width) {
545 if(_lines.isEmpty()) {
546 updateSceneRect(QRectF(0, 0, width, 0));
550 // we hide day change messages at the top by making the scene rect smaller
551 // and by calling QGraphicsItem::hide() on all leading day change messages
552 // the first one is needed to ensure proper scrollbar ranges
553 // the second for cases where the viewport is larger then the set scenerect
554 // (in this case the items are shown anyways)
555 if(_firstLineRow == -1) {
556 int numRows = model()->rowCount();
558 QModelIndex firstLineIdx;
559 while(_firstLineRow < numRows) {
560 firstLineIdx = model()->index(_firstLineRow, 0);
561 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
563 _lines.at(_firstLineRow)->hide();
568 // the following call should be safe. If it crashes something went wrong during insert/remove
569 if(_firstLineRow < _lines.count()) {
570 ChatLine *firstLine = _lines.at(_firstLineRow);
571 ChatLine *lastLine = _lines.last();
572 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
575 updateSceneRect(QRectF(0, 0, width, 0));
579 void ChatScene::updateSceneRect(const QRectF &rect) {
585 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
591 if(webPreview.parentItem != parentItem)
592 webPreview.parentItem = parentItem;
594 if(webPreview.url != url) {
595 webPreview.url = url;
596 // load a new web view and delete the old one (if exists)
597 if(webPreview.previewItem && webPreview.previewItem->scene()) {
598 removeItem(webPreview.previewItem);
599 delete webPreview.previewItem;
601 webPreview.previewItem = new WebPreviewItem(url);
602 webPreview.delayTimer.start(2000);
603 webPreview.deleteTimer.stop();
604 } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
605 // we just have to readd the item to the scene
606 webPreview.delayTimer.start(2000);
607 webPreview.deleteTimer.stop();
609 if(webPreview.urlRect != urlRect) {
610 webPreview.urlRect = urlRect;
611 qreal previewY = urlRect.bottom();
612 qreal previewX = urlRect.x();
613 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
614 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
616 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
617 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
619 webPreview.previewItem->setPos(previewX, previewY);
624 void ChatScene::showWebPreviewEvent() {
626 if(webPreview.previewItem)
627 addItem(webPreview.previewItem);
631 void ChatScene::clearWebPreview(ChatItem *parentItem) {
635 if(parentItem == 0 || webPreview.parentItem == parentItem) {
636 if(webPreview.previewItem && webPreview.previewItem->scene()) {
637 removeItem(webPreview.previewItem);
638 webPreview.deleteTimer.start();
640 webPreview.delayTimer.stop();
645 void ChatScene::deleteWebPreviewEvent() {
647 if(webPreview.previewItem) {
648 delete webPreview.previewItem;
649 webPreview.previewItem = 0;
651 webPreview.parentItem = 0;
652 webPreview.url = QString();
653 webPreview.urlRect = QRectF();