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(handlePositionChanged(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(handlePositionChanged(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 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
270 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
273 // when searching for the first non-date-line we have to take into account that our
274 // model still contains the just removed lines so we cannot simply call updateSceneRect()
275 int numRows = model()->rowCount();
276 QModelIndex firstLineIdx;
278 bool needOffset = false;
281 if(_firstLineRow >= start && _firstLineRow <= end) {
282 _firstLineRow = end + 1;
285 firstLineIdx = model()->index(_firstLineRow, 0);
286 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
289 _firstLineRow -= end - start + 1;
293 void ChatScene::updateForViewport(qreal width, qreal height) {
294 _viewportHeight = height;
298 // setWidth is used for 2 things:
299 // a) updating the scene to fit the width of the corresponding view
300 // b) to update the positions of the items if a columhandle has changed it's position
301 // forceReposition is true in the second case
302 // this method features some codeduplication for the sake of performance
303 void ChatScene::setWidth(qreal width, bool forceReposition) {
304 if(width == _sceneRect.width() && !forceReposition)
307 // clock_t startT = clock();
309 // disabling the index while doing this complex updates is about
310 // 2 to 10 times faster!
311 setItemIndexMethod(QGraphicsScene::NoIndex);
313 qreal linePos = _sceneRect.y() + _sceneRect.height();
314 QList<ChatLine *>::iterator lineIter = _lines.end();
315 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
317 qreal lineHeight = 0;
318 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
320 if(forceReposition) {
321 qreal timestampWidth = firstColumnHandle()->sceneLeft();
322 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
323 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
324 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
325 while(lineIter != lineIterBegin) {
328 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
329 linePos -= lineHeight;
330 line->setPos(0, linePos);
333 while(lineIter != lineIterBegin) {
336 lineHeight = line->setGeometryByWidth(width, contentsWidth);
337 linePos -= lineHeight;
338 line->setPos(0, linePos);
341 setItemIndexMethod(QGraphicsScene::BspTreeIndex);
343 updateSceneRect(width);
346 // clock_t endT = clock();
347 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
350 void ChatScene::handlePositionChanged(qreal xpos) {
351 bool first = (sender() == _firstColHandle);
354 oldx = _firstColHandlePos;
355 _firstColHandlePos = xpos;
357 oldx = _secondColHandlePos;
358 _secondColHandlePos = xpos;
361 ChatViewSettings viewSettings(this);
362 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
363 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
365 ChatViewSettings defaultSettings;
366 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
367 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
369 setWidth(width(), true); // readjust all chatlines
370 // we get ugly redraw errors if we don't update this explicitly... :(
371 // width() should be the same for both handles, so just use _firstColHandle regardless
372 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
375 void ChatScene::setHandleXLimits() {
376 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
377 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
380 void ChatScene::setSelectingItem(ChatItem *item) {
381 if(_selectingItem) _selectingItem->clearSelection();
382 _selectingItem = item;
385 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
386 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
387 _selectionStartCol = _selectionMinCol = item->column();
389 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
390 updateSelection(item->mapToScene(itemPos));
393 void ChatScene::updateSelection(const QPointF &pos) {
394 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
395 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
396 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, pos.y())));
397 if(!contentItem) return;
399 int curRow = contentItem->row();
401 if(pos.x() > _secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
402 else if(pos.x() > _firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
403 else curColumn = ChatLineModel::TimestampColumn;
405 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
406 if(minColumn != _selectionMinCol) {
407 _selectionMinCol = minColumn;
408 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
409 _lines[l]->setSelected(true, minColumn);
412 int newstart = qMin(curRow, _firstSelectionRow);
413 int newend = qMax(curRow, _firstSelectionRow);
414 if(newstart < _selectionStart) {
415 for(int l = newstart; l < _selectionStart; l++)
416 _lines[l]->setSelected(true, minColumn);
418 if(newstart > _selectionStart) {
419 for(int l = _selectionStart; l < newstart; l++)
420 _lines[l]->setSelected(false);
422 if(newend > _selectionEnd) {
423 for(int l = _selectionEnd+1; l <= newend; l++)
424 _lines[l]->setSelected(true, minColumn);
426 if(newend < _selectionEnd) {
427 for(int l = newend+1; l <= _selectionEnd; l++)
428 _lines[l]->setSelected(false);
431 _selectionStart = newstart;
432 _selectionEnd = newend;
433 _lastSelectionRow = curRow;
435 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
436 if(!_selectingItem) {
437 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
440 _lines[curRow]->setSelected(false);
441 _isSelecting = false;
442 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
446 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
447 if(_isSelecting && event->buttons() == Qt::LeftButton) {
448 updateSelection(event->scenePos());
451 QGraphicsScene::mouseMoveEvent(event);
455 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
456 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
457 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
458 _lines[l]->setSelected(false);
460 _selectionStart = -1;
461 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
463 QGraphicsScene::mousePressEvent(event);
467 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
468 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
469 putToClipboard(selectionToString());
470 _isSelecting = false;
473 QGraphicsScene::mouseReleaseEvent(event);
477 void ChatScene::putToClipboard(const QString &selection) {
478 // TODO Configure clipboards
480 QApplication::clipboard()->setText(selection, QClipboard::Selection);
483 QApplication::clipboard()->setText(selection);
487 //!\brief Convert current selection to human-readable string.
488 QString ChatScene::selectionToString() const {
489 //TODO Make selection format configurable!
490 if(!_isSelecting) return QString();
491 int start = qMin(_selectionStart, _selectionEnd);
492 int end = qMax(_selectionStart, _selectionEnd);
493 if(start < 0 || end >= _lines.count()) {
494 qDebug() << "Invalid selection range:" << start << end;
498 for(int l = start; l <= end; l++) {
499 if(_selectionMinCol == ChatLineModel::TimestampColumn)
500 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
501 if(_selectionMinCol <= ChatLineModel::SenderColumn)
502 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
503 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
508 void ChatScene::requestBacklog() {
509 static const int REQUEST_COUNT = 500;
510 int backlogSize = model()->rowCount();
511 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
512 QModelIndex msgIdx = model()->index(0, 0);
513 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
514 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
516 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
517 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
518 _lastBacklogSize = backlogSize;
519 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
523 int ChatScene::sectionByScenePos(int x) {
524 if(x < _firstColHandle->x())
525 return ChatLineModel::TimestampColumn;
526 if(x < _secondColHandle->x())
527 return ChatLineModel::SenderColumn;
529 return ChatLineModel::ContentsColumn;
532 void ChatScene::updateSceneRect() {
533 if(_lines.isEmpty()) {
534 updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
538 // we hide day change messages at the top by making the scene rect smaller
539 // and by calling QGraphicsItem::hide() on all leading day change messages
540 // the first one is needed to ensure proper scrollbar ranges
541 // the second for cases where the viewport is larger then the set scenerect
542 // (in this case the items are shown anyways)
543 if(_firstLineRow == -1) {
544 int numRows = model()->rowCount();
546 QModelIndex firstLineIdx;
547 while(_firstLineRow < numRows) {
548 firstLineIdx = model()->index(_firstLineRow, 0);
549 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
551 _lines.at(_firstLineRow)->hide();
556 // the following call should be safe. If it crashes something went wrong during insert/remove
557 ChatLine *firstLine = _lines.at(_firstLineRow);
558 ChatLine *lastLine = _lines.last();
559 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
562 void ChatScene::updateSceneRect(qreal width) {
563 _sceneRect.setWidth(width);
567 void ChatScene::updateSceneRect(const QRectF &rect) {
573 void ChatScene::customEvent(QEvent *event) {
574 switch(event->type()) {
580 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
586 if(webPreview.parentItem != parentItem)
587 webPreview.parentItem = parentItem;
589 if(webPreview.url != url) {
590 webPreview.url = url;
591 // load a new web view and delete the old one (if exists)
592 if(webPreview.previewItem && webPreview.previewItem->scene()) {
593 removeItem(webPreview.previewItem);
594 delete webPreview.previewItem;
596 webPreview.previewItem = new WebPreviewItem(url);
597 webPreview.delayTimer.start(2000);
598 webPreview.deleteTimer.stop();
599 } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
600 // we just have to readd the item to the scene
601 webPreview.delayTimer.start(2000);
602 webPreview.deleteTimer.stop();
604 if(webPreview.urlRect != urlRect) {
605 webPreview.urlRect = urlRect;
606 qreal previewY = urlRect.bottom();
607 qreal previewX = urlRect.x();
608 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
609 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
611 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
612 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
614 webPreview.previewItem->setPos(previewX, previewY);
619 void ChatScene::showWebPreviewEvent() {
621 if(webPreview.previewItem)
622 addItem(webPreview.previewItem);
626 void ChatScene::clearWebPreview(ChatItem *parentItem) {
630 if(parentItem == 0 || webPreview.parentItem == parentItem) {
631 if(webPreview.previewItem && webPreview.previewItem->scene()) {
632 removeItem(webPreview.previewItem);
633 webPreview.deleteTimer.start();
635 webPreview.delayTimer.stop();
640 void ChatScene::deleteWebPreviewEvent() {
642 if(webPreview.previewItem) {
643 delete webPreview.previewItem;
644 webPreview.previewItem = 0;
646 webPreview.parentItem = 0;
647 webPreview.url = QString();
648 webPreview.urlRect = QRectF();