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()));
97 setItemIndexMethod(QGraphicsScene::NoIndex);
100 ChatScene::~ChatScene() {
103 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
105 // QModelIndex sidx = model()->index(start, 0);
106 // QModelIndex eidx = model()->index(end, 0);
107 // qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
110 qreal y = _sceneRect.y();
111 qreal width = _sceneRect.width();
113 bool atBottom = false;
114 bool moveTop = false;
116 if(start > 0 && start < _lines.count()) {
117 y = _lines.value(start)->y();
120 if(start == _lines.count()) {
121 y = _sceneRect.bottom();
126 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
127 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
128 qreal timestampWidth = firstColumnHandle()->sceneLeft();
129 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
130 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
133 for(int i = end; i >= start; i--) {
134 ChatLine *line = new ChatLine(i, model(),
136 timestampWidth, senderWidth, contentsWidth,
137 senderPos, contentsPos);
139 line->setPos(0, y-h);
140 _lines.insert(start, line);
144 for(int i = start; i <= end; i++) {
145 ChatLine *line = new ChatLine(i, model(),
147 timestampWidth, senderWidth, contentsWidth,
148 senderPos, contentsPos);
149 line->setPos(0, y+h);
151 _lines.insert(i, line);
156 // update existing items
157 for(int i = end+1; i < _lines.count(); i++) {
158 _lines[i]->setRow(i);
162 if(_selectionStart >= 0) {
163 int offset = end - start + 1;
164 if(_selectionStart >= start) _selectionStart += offset;
165 if(_selectionEnd >= start) _selectionEnd += offset;
166 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
167 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
170 // neither pre- or append means we have to do dirty work: move items...
171 if(!(atTop || atBottom)) {
174 int moveEnd = _lines.count() - 1;
175 // move top means: moving 0 to end (aka: end + 1)
176 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
177 if(end + 1 < _lines.count() - end - 1) {
187 for(int i = moveStart; i <= moveEnd; i++) {
189 line->setPos(0, line->pos().y() + offset);
193 // check if all went right
194 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
195 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
198 if(start < _firstLineRow) {
199 int prevFirstLineRow = _firstLineRow + (end - start + 1);
200 for(int i = end + 1; i < prevFirstLineRow; i++) {
201 _lines.at(i)->show();
204 // force new search for first proper line
208 if(atBottom || (!atTop && !moveTop)) {
209 emit lastLineChanged(_lines.last(), h);
213 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
216 qreal h = 0; // total height of removed items;
218 bool atTop = (start == 0);
219 bool atBottom = (end == _lines.count() - 1);
220 bool moveTop = false;
222 // remove items from scene
223 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
224 int lineCount = start;
225 while(lineIter != _lines.end() && lineCount <= end) {
226 h += (*lineIter)->height();
228 lineIter = _lines.erase(lineIter);
232 // update rows of remaining chatlines
233 for(int i = start; i < _lines.count(); i++) {
234 _lines.at(i)->setRow(i);
238 if(_selectionStart >= 0) {
239 int offset = end - start + 1;
240 if(_selectionStart >= start)
241 _selectionStart -= offset;
242 if(_selectionEnd >= start)
243 _selectionEnd -= offset;
244 if(_firstSelectionRow >= start)
245 _firstSelectionRow -= offset;
246 if(_lastSelectionRow >= start)
247 _lastSelectionRow -= offset;
250 // neither removing at bottom or top means we have to move items...
251 if(!(atTop || atBottom)) {
254 int moveEnd = _lines.count() - 1;
255 if(start < _lines.count() - start) {
265 for(int i = moveStart; i <= moveEnd; i++) {
267 line->setPos(0, line->pos().y() + offset);
271 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
274 // when searching for the first non-date-line we have to take into account that our
275 // model still contains the just removed lines so we cannot simply call updateSceneRect()
276 int numRows = model()->rowCount();
277 QModelIndex firstLineIdx;
279 bool needOffset = false;
282 if(_firstLineRow >= start && _firstLineRow <= end) {
283 _firstLineRow = end + 1;
286 firstLineIdx = model()->index(_firstLineRow, 0);
287 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
290 _firstLineRow -= end - start + 1;
294 void ChatScene::updateForViewport(qreal width, qreal height) {
295 _viewportHeight = height;
299 void ChatScene::setWidth(qreal width) {
300 if(width == _sceneRect.width())
303 // clock_t startT = clock();
305 // disabling the index while doing this complex updates is about
306 // 2 to 10 times faster!
307 //setItemIndexMethod(QGraphicsScene::NoIndex);
309 QList<ChatLine *>::iterator lineIter = _lines.end();
310 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
311 qreal linePos = _sceneRect.y() + _sceneRect.height();
312 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
313 while(lineIter != lineIterBegin) {
315 (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
317 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
319 updateSceneRect(width);
322 // clock_t endT = clock();
323 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
326 void ChatScene::firstHandlePositionChanged(qreal xpos) {
327 if(_firstColHandlePos == xpos)
330 _firstColHandlePos = xpos;
331 ChatViewSettings viewSettings(this);
332 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
333 ChatViewSettings defaultSettings;
334 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
336 // clock_t startT = clock();
338 // disabling the index while doing this complex updates is about
339 // 2 to 10 times faster!
340 //setItemIndexMethod(QGraphicsScene::NoIndex);
342 QList<ChatLine *>::iterator lineIter = _lines.end();
343 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
344 qreal timestampWidth = firstColumnHandle()->sceneLeft();
345 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
346 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
348 while(lineIter != lineIterBegin) {
350 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
352 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
356 // clock_t endT = clock();
357 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
360 void ChatScene::secondHandlePositionChanged(qreal xpos) {
361 if(_secondColHandlePos == xpos)
364 _secondColHandlePos = xpos;
365 ChatViewSettings viewSettings(this);
366 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
367 ChatViewSettings defaultSettings;
368 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
370 // clock_t startT = clock();
372 // disabling the index while doing this complex updates is about
373 // 2 to 10 times faster!
374 //setItemIndexMethod(QGraphicsScene::NoIndex);
376 QList<ChatLine *>::iterator lineIter = _lines.end();
377 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
378 qreal linePos = _sceneRect.y() + _sceneRect.height();
379 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
380 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
381 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
382 while(lineIter != lineIterBegin) {
384 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
386 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
390 // clock_t endT = clock();
391 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
394 void ChatScene::setHandleXLimits() {
395 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
396 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
399 void ChatScene::setSelectingItem(ChatItem *item) {
400 if(_selectingItem) _selectingItem->clearSelection();
401 _selectingItem = item;
404 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
405 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
406 _selectionStartCol = _selectionMinCol = item->column();
408 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
409 updateSelection(item->mapToScene(itemPos));
412 void ChatScene::updateSelection(const QPointF &pos) {
413 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
414 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
415 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, pos.y())));
416 if(!contentItem) return;
418 int curRow = contentItem->row();
420 if(pos.x() > _secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
421 else if(pos.x() > _firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
422 else curColumn = ChatLineModel::TimestampColumn;
424 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
425 if(minColumn != _selectionMinCol) {
426 _selectionMinCol = minColumn;
427 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
428 _lines[l]->setSelected(true, minColumn);
431 int newstart = qMin(curRow, _firstSelectionRow);
432 int newend = qMax(curRow, _firstSelectionRow);
433 if(newstart < _selectionStart) {
434 for(int l = newstart; l < _selectionStart; l++)
435 _lines[l]->setSelected(true, minColumn);
437 if(newstart > _selectionStart) {
438 for(int l = _selectionStart; l < newstart; l++)
439 _lines[l]->setSelected(false);
441 if(newend > _selectionEnd) {
442 for(int l = _selectionEnd+1; l <= newend; l++)
443 _lines[l]->setSelected(true, minColumn);
445 if(newend < _selectionEnd) {
446 for(int l = newend+1; l <= _selectionEnd; l++)
447 _lines[l]->setSelected(false);
450 _selectionStart = newstart;
451 _selectionEnd = newend;
452 _lastSelectionRow = curRow;
454 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
455 if(!_selectingItem) {
456 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
459 _lines[curRow]->setSelected(false);
460 _isSelecting = false;
461 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
465 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
466 if(_isSelecting && event->buttons() == Qt::LeftButton) {
467 updateSelection(event->scenePos());
470 QGraphicsScene::mouseMoveEvent(event);
474 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
475 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
476 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
477 _lines[l]->setSelected(false);
479 _selectionStart = -1;
480 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
482 QGraphicsScene::mousePressEvent(event);
486 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
487 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
488 putToClipboard(selectionToString());
489 _isSelecting = false;
492 QGraphicsScene::mouseReleaseEvent(event);
496 void ChatScene::putToClipboard(const QString &selection) {
497 // TODO Configure clipboards
499 QApplication::clipboard()->setText(selection, QClipboard::Selection);
502 QApplication::clipboard()->setText(selection);
506 //!\brief Convert current selection to human-readable string.
507 QString ChatScene::selectionToString() const {
508 //TODO Make selection format configurable!
509 if(!_isSelecting) return QString();
510 int start = qMin(_selectionStart, _selectionEnd);
511 int end = qMax(_selectionStart, _selectionEnd);
512 if(start < 0 || end >= _lines.count()) {
513 qDebug() << "Invalid selection range:" << start << end;
517 for(int l = start; l <= end; l++) {
518 if(_selectionMinCol == ChatLineModel::TimestampColumn)
519 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
520 if(_selectionMinCol <= ChatLineModel::SenderColumn)
521 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
522 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
527 void ChatScene::requestBacklog() {
528 static const int REQUEST_COUNT = 500;
529 int backlogSize = model()->rowCount();
530 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
531 QModelIndex msgIdx = model()->index(0, 0);
532 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
533 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
535 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
536 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
537 _lastBacklogSize = backlogSize;
538 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
542 int ChatScene::sectionByScenePos(int x) {
543 if(x < _firstColHandle->x())
544 return ChatLineModel::TimestampColumn;
545 if(x < _secondColHandle->x())
546 return ChatLineModel::SenderColumn;
548 return ChatLineModel::ContentsColumn;
551 void ChatScene::updateSceneRect(qreal width) {
552 if(_lines.isEmpty()) {
553 updateSceneRect(QRectF(0, 0, width, 0));
557 // we hide day change messages at the top by making the scene rect smaller
558 // and by calling QGraphicsItem::hide() on all leading day change messages
559 // the first one is needed to ensure proper scrollbar ranges
560 // the second for cases where the viewport is larger then the set scenerect
561 // (in this case the items are shown anyways)
562 if(_firstLineRow == -1) {
563 int numRows = model()->rowCount();
565 QModelIndex firstLineIdx;
566 while(_firstLineRow < numRows) {
567 firstLineIdx = model()->index(_firstLineRow, 0);
568 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
570 _lines.at(_firstLineRow)->hide();
575 // the following call should be safe. If it crashes something went wrong during insert/remove
576 ChatLine *firstLine = _lines.at(_firstLineRow);
577 ChatLine *lastLine = _lines.last();
578 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
581 void ChatScene::updateSceneRect(const QRectF &rect) {
587 void ChatScene::customEvent(QEvent *event) {
588 switch(event->type()) {
594 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
600 if(webPreview.parentItem != parentItem)
601 webPreview.parentItem = parentItem;
603 if(webPreview.url != url) {
604 webPreview.url = url;
605 // load a new web view and delete the old one (if exists)
606 if(webPreview.previewItem && webPreview.previewItem->scene()) {
607 removeItem(webPreview.previewItem);
608 delete webPreview.previewItem;
610 webPreview.previewItem = new WebPreviewItem(url);
611 webPreview.delayTimer.start(2000);
612 webPreview.deleteTimer.stop();
613 } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
614 // we just have to readd the item to the scene
615 webPreview.delayTimer.start(2000);
616 webPreview.deleteTimer.stop();
618 if(webPreview.urlRect != urlRect) {
619 webPreview.urlRect = urlRect;
620 qreal previewY = urlRect.bottom();
621 qreal previewX = urlRect.x();
622 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
623 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
625 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
626 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
628 webPreview.previewItem->setPos(previewX, previewY);
633 void ChatScene::showWebPreviewEvent() {
635 if(webPreview.previewItem)
636 addItem(webPreview.previewItem);
640 void ChatScene::clearWebPreview(ChatItem *parentItem) {
644 if(parentItem == 0 || webPreview.parentItem == parentItem) {
645 if(webPreview.previewItem && webPreview.previewItem->scene()) {
646 removeItem(webPreview.previewItem);
647 webPreview.deleteTimer.start();
649 webPreview.delayTimer.stop();
654 void ChatScene::deleteWebPreviewEvent() {
656 if(webPreview.previewItem) {
657 delete webPreview.previewItem;
658 webPreview.previewItem = 0;
660 webPreview.parentItem = 0;
661 webPreview.url = QString();
662 webPreview.urlRect = QRectF();