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),
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)));
78 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
82 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
83 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
84 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
85 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
87 if(model->rowCount() > 0)
88 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
91 webPreview.delayTimer.setSingleShot(true);
92 connect(&webPreview.delayTimer, SIGNAL(timeout()), this, SLOT(showWebPreviewEvent()));
93 webPreview.deleteTimer.setInterval(600000);
94 connect(&webPreview.deleteTimer, SIGNAL(timeout()), this, SLOT(deleteWebPreviewEvent()));
98 ChatScene::~ChatScene() {
101 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
103 // QModelIndex sidx = model()->index(start, 0);
104 // QModelIndex eidx = model()->index(end, 0);
105 // qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
108 qreal y = _sceneRect.y();
109 qreal width = _sceneRect.width();
111 bool atBottom = false;
112 bool moveTop = false;
114 if(start > 0 && start < _lines.count()) {
115 y = _lines.value(start)->y();
118 if(start == _lines.count()) {
119 y = _sceneRect.bottom();
124 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
125 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
126 qreal timestampWidth = firstColumnHandle()->sceneLeft();
127 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
128 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
131 for(int i = end; i >= start; i--) {
132 ChatLine *line = new ChatLine(i, model(),
134 timestampWidth, senderWidth, contentsWidth,
135 senderPos, contentsPos);
137 line->setPos(0, y-h);
138 _lines.insert(start, line);
142 for(int i = start; i <= end; i++) {
143 ChatLine *line = new ChatLine(i, model(),
145 timestampWidth, senderWidth, contentsWidth,
146 senderPos, contentsPos);
147 line->setPos(0, y+h);
149 _lines.insert(i, line);
154 // update existing items
155 for(int i = end+1; i < _lines.count(); i++) {
156 _lines[i]->setRow(i);
160 if(_selectionStart >= 0) {
161 int offset = end - start + 1;
162 if(_selectionStart >= start) _selectionStart += offset;
163 if(_selectionEnd >= start) _selectionEnd += offset;
164 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
165 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
168 // neither pre- or append means we have to do dirty work: move items...
169 if(!(atTop || atBottom)) {
172 int moveEnd = _lines.count() - 1;
173 // move top means: moving 0 to end (aka: end + 1)
174 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
175 if(end + 1 < _lines.count() - end - 1) {
185 for(int i = moveStart; i <= moveEnd; i++) {
187 line->setPos(0, line->pos().y() + offset);
191 // check if all went right
192 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
193 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
196 if(start < _firstLineRow) {
197 int prevFirstLineRow = _firstLineRow + (end - start + 1);
198 for(int i = end + 1; i < prevFirstLineRow; i++) {
199 _lines.at(i)->show();
202 // force new search for first proper line
206 if(atBottom || (!atTop && !moveTop)) {
207 emit lastLineChanged(_lines.last(), h);
211 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
214 qreal h = 0; // total height of removed items;
216 bool atTop = (start == 0);
217 bool atBottom = (end == _lines.count() - 1);
218 bool moveTop = false;
220 // remove items from scene
221 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
222 int lineCount = start;
223 while(lineIter != _lines.end() && lineCount <= end) {
224 h += (*lineIter)->height();
226 lineIter = _lines.erase(lineIter);
230 // update rows of remaining chatlines
231 for(int i = start; i < _lines.count(); i++) {
232 _lines.at(i)->setRow(i);
236 if(_selectionStart >= 0) {
237 int offset = end - start + 1;
238 if(_selectionStart >= start)
239 _selectionStart -= offset;
240 if(_selectionEnd >= start)
241 _selectionEnd -= offset;
242 if(_firstSelectionRow >= start)
243 _firstSelectionRow -= offset;
244 if(_lastSelectionRow >= start)
245 _lastSelectionRow -= offset;
248 // neither removing at bottom or top means we have to move items...
249 if(!(atTop || atBottom)) {
252 int moveEnd = _lines.count() - 1;
253 if(start < _lines.count() - start) {
263 for(int i = moveStart; i <= moveEnd; i++) {
265 line->setPos(0, line->pos().y() + offset);
269 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
272 // when searching for the first non-date-line we have to take into account that our
273 // model still contains the just removed lines so we cannot simply call updateSceneRect()
274 int numRows = model()->rowCount();
275 QModelIndex firstLineIdx;
277 bool needOffset = false;
280 if(_firstLineRow >= start && _firstLineRow <= end) {
281 _firstLineRow = end + 1;
284 firstLineIdx = model()->index(_firstLineRow, 0);
285 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
288 _firstLineRow -= end - start + 1;
292 void ChatScene::updateForViewport(qreal width, qreal height) {
293 _viewportHeight = height;
297 void ChatScene::setWidth(qreal width) {
298 if(width == _sceneRect.width())
301 // clock_t startT = clock();
303 // disabling the index while doing this complex updates is about
304 // 2 to 10 times faster!
305 setItemIndexMethod(QGraphicsScene::NoIndex);
307 QList<ChatLine *>::iterator lineIter = _lines.end();
308 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
309 qreal linePos = _sceneRect.y() + _sceneRect.height();
310 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
311 while(lineIter != lineIterBegin) {
313 (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
315 setItemIndexMethod(QGraphicsScene::BspTreeIndex);
317 updateSceneRect(width);
320 // clock_t endT = clock();
321 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
324 void ChatScene::firstHandlePositionChanged(qreal xpos) {
325 if(_firstColHandlePos == xpos)
328 _firstColHandlePos = xpos;
329 ChatViewSettings viewSettings(this);
330 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
331 ChatViewSettings defaultSettings;
332 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
334 // clock_t startT = clock();
336 // disabling the index while doing this complex updates is about
337 // 2 to 10 times faster!
338 setItemIndexMethod(QGraphicsScene::NoIndex);
340 QList<ChatLine *>::iterator lineIter = _lines.end();
341 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
342 qreal timestampWidth = firstColumnHandle()->sceneLeft();
343 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
344 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
346 while(lineIter != lineIterBegin) {
348 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
350 setItemIndexMethod(QGraphicsScene::BspTreeIndex);
354 // clock_t endT = clock();
355 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
358 void ChatScene::secondHandlePositionChanged(qreal xpos) {
359 if(_secondColHandlePos == xpos)
362 _secondColHandlePos = xpos;
363 ChatViewSettings viewSettings(this);
364 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
365 ChatViewSettings defaultSettings;
366 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
368 // clock_t startT = clock();
370 // disabling the index while doing this complex updates is about
371 // 2 to 10 times faster!
372 setItemIndexMethod(QGraphicsScene::NoIndex);
374 QList<ChatLine *>::iterator lineIter = _lines.end();
375 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
376 qreal linePos = _sceneRect.y() + _sceneRect.height();
377 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
378 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
379 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
380 while(lineIter != lineIterBegin) {
382 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
384 setItemIndexMethod(QGraphicsScene::BspTreeIndex);
388 // clock_t endT = clock();
389 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
392 void ChatScene::setHandleXLimits() {
393 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
394 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
397 void ChatScene::setSelectingItem(ChatItem *item) {
398 if(_selectingItem) _selectingItem->clearSelection();
399 _selectingItem = item;
402 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
403 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
404 _selectionStartCol = _selectionMinCol = item->column();
406 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
407 updateSelection(item->mapToScene(itemPos));
410 void ChatScene::updateSelection(const QPointF &pos) {
411 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
412 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
413 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, pos.y())));
414 if(!contentItem) return;
416 int curRow = contentItem->row();
418 if(pos.x() > _secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
419 else if(pos.x() > _firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
420 else curColumn = ChatLineModel::TimestampColumn;
422 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
423 if(minColumn != _selectionMinCol) {
424 _selectionMinCol = minColumn;
425 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
426 _lines[l]->setSelected(true, minColumn);
429 int newstart = qMin(curRow, _firstSelectionRow);
430 int newend = qMax(curRow, _firstSelectionRow);
431 if(newstart < _selectionStart) {
432 for(int l = newstart; l < _selectionStart; l++)
433 _lines[l]->setSelected(true, minColumn);
435 if(newstart > _selectionStart) {
436 for(int l = _selectionStart; l < newstart; l++)
437 _lines[l]->setSelected(false);
439 if(newend > _selectionEnd) {
440 for(int l = _selectionEnd+1; l <= newend; l++)
441 _lines[l]->setSelected(true, minColumn);
443 if(newend < _selectionEnd) {
444 for(int l = newend+1; l <= _selectionEnd; l++)
445 _lines[l]->setSelected(false);
448 _selectionStart = newstart;
449 _selectionEnd = newend;
450 _lastSelectionRow = curRow;
452 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
453 if(!_selectingItem) {
454 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
457 _lines[curRow]->setSelected(false);
458 _isSelecting = false;
459 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
463 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
464 if(_isSelecting && event->buttons() == Qt::LeftButton) {
465 updateSelection(event->scenePos());
468 QGraphicsScene::mouseMoveEvent(event);
472 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
473 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
474 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
475 _lines[l]->setSelected(false);
477 _selectionStart = -1;
478 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
480 QGraphicsScene::mousePressEvent(event);
484 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
485 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
486 putToClipboard(selectionToString());
487 _isSelecting = false;
490 QGraphicsScene::mouseReleaseEvent(event);
494 void ChatScene::putToClipboard(const QString &selection) {
495 // TODO Configure clipboards
497 QApplication::clipboard()->setText(selection, QClipboard::Selection);
500 QApplication::clipboard()->setText(selection);
504 //!\brief Convert current selection to human-readable string.
505 QString ChatScene::selectionToString() const {
506 //TODO Make selection format configurable!
507 if(!_isSelecting) return QString();
508 int start = qMin(_selectionStart, _selectionEnd);
509 int end = qMax(_selectionStart, _selectionEnd);
510 if(start < 0 || end >= _lines.count()) {
511 qDebug() << "Invalid selection range:" << start << end;
515 for(int l = start; l <= end; l++) {
516 if(_selectionMinCol == ChatLineModel::TimestampColumn)
517 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
518 if(_selectionMinCol <= ChatLineModel::SenderColumn)
519 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
520 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
525 void ChatScene::requestBacklog() {
526 static const int REQUEST_COUNT = 500;
527 int backlogSize = model()->rowCount();
528 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
529 QModelIndex msgIdx = model()->index(0, 0);
530 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
531 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
533 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
534 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
535 _lastBacklogSize = backlogSize;
536 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
540 int ChatScene::sectionByScenePos(int x) {
541 if(x < _firstColHandle->x())
542 return ChatLineModel::TimestampColumn;
543 if(x < _secondColHandle->x())
544 return ChatLineModel::SenderColumn;
546 return ChatLineModel::ContentsColumn;
549 void ChatScene::updateSceneRect(qreal width) {
550 if(_lines.isEmpty()) {
551 updateSceneRect(QRectF(0, 0, width, 0));
555 // we hide day change messages at the top by making the scene rect smaller
556 // and by calling QGraphicsItem::hide() on all leading day change messages
557 // the first one is needed to ensure proper scrollbar ranges
558 // the second for cases where the viewport is larger then the set scenerect
559 // (in this case the items are shown anyways)
560 if(_firstLineRow == -1) {
561 int numRows = model()->rowCount();
563 QModelIndex firstLineIdx;
564 while(_firstLineRow < numRows) {
565 firstLineIdx = model()->index(_firstLineRow, 0);
566 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
568 _lines.at(_firstLineRow)->hide();
573 // the following call should be safe. If it crashes something went wrong during insert/remove
574 ChatLine *firstLine = _lines.at(_firstLineRow);
575 ChatLine *lastLine = _lines.last();
576 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
579 void ChatScene::updateSceneRect(const QRectF &rect) {
585 void ChatScene::customEvent(QEvent *event) {
586 switch(event->type()) {
592 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
598 if(webPreview.parentItem != parentItem)
599 webPreview.parentItem = parentItem;
601 if(webPreview.url != url) {
602 webPreview.url = url;
603 // load a new web view and delete the old one (if exists)
604 if(webPreview.previewItem && webPreview.previewItem->scene()) {
605 removeItem(webPreview.previewItem);
606 delete webPreview.previewItem;
608 webPreview.previewItem = new WebPreviewItem(url);
609 webPreview.delayTimer.start(2000);
610 webPreview.deleteTimer.stop();
611 } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
612 // we just have to readd the item to the scene
613 webPreview.delayTimer.start(2000);
614 webPreview.deleteTimer.stop();
616 if(webPreview.urlRect != urlRect) {
617 webPreview.urlRect = urlRect;
618 qreal previewY = urlRect.bottom();
619 qreal previewX = urlRect.x();
620 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
621 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
623 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
624 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
626 webPreview.previewItem->setPos(previewX, previewY);
631 void ChatScene::showWebPreviewEvent() {
633 if(webPreview.previewItem)
634 addItem(webPreview.previewItem);
638 void ChatScene::clearWebPreview(ChatItem *parentItem) {
642 if(parentItem == 0 || webPreview.parentItem == parentItem) {
643 if(webPreview.previewItem && webPreview.previewItem->scene()) {
644 removeItem(webPreview.previewItem);
645 webPreview.deleteTimer.start();
647 webPreview.delayTimer.stop();
652 void ChatScene::deleteWebPreviewEvent() {
654 if(webPreview.previewItem) {
655 delete webPreview.previewItem;
656 webPreview.previewItem = 0;
658 webPreview.parentItem = 0;
659 webPreview.url = QString();
660 webPreview.urlRect = QRectF();