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...
173 int moveEnd = _lines.count() - 1;
175 if(!(atTop || atBottom)) {
176 // int moveStart = 0;
177 // int moveEnd = _lines.count() - 1;
179 // move top means: moving 0 to end (aka: end + 1)
180 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
181 if(end + 1 < _lines.count() - end - 1) {
191 for(int i = moveStart; i <= moveEnd; i++) {
193 line->setPos(0, line->pos().y() + offset);
197 // check if all went right
198 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
199 //Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
200 if(end + 1 < _lines.count()) {
201 if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
202 qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
203 qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
204 qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
205 qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
211 if(start < _firstLineRow) {
212 int prevFirstLineRow = _firstLineRow + (end - start + 1);
213 for(int i = end + 1; i < prevFirstLineRow; i++) {
214 _lines.at(i)->show();
217 // force new search for first proper line
221 if(atBottom || (!atTop && !moveTop)) {
222 emit lastLineChanged(_lines.last(), h);
226 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
229 qreal h = 0; // total height of removed items;
231 bool atTop = (start == 0);
232 bool atBottom = (end == _lines.count() - 1);
233 bool moveTop = false;
235 // remove items from scene
236 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
237 int lineCount = start;
238 while(lineIter != _lines.end() && lineCount <= end) {
239 h += (*lineIter)->height();
241 lineIter = _lines.erase(lineIter);
245 // update rows of remaining chatlines
246 for(int i = start; i < _lines.count(); i++) {
247 _lines.at(i)->setRow(i);
251 if(_selectionStart >= 0) {
252 int offset = end - start + 1;
253 if(_selectionStart >= start)
254 _selectionStart -= offset;
255 if(_selectionEnd >= start)
256 _selectionEnd -= offset;
257 if(_firstSelectionRow >= start)
258 _firstSelectionRow -= offset;
259 if(_lastSelectionRow >= start)
260 _lastSelectionRow -= offset;
263 // neither removing at bottom or top means we have to move items...
264 if(!(atTop || atBottom)) {
267 int moveEnd = _lines.count() - 1;
268 if(start < _lines.count() - start) {
278 for(int i = moveStart; i <= moveEnd; i++) {
280 line->setPos(0, line->pos().y() + offset);
284 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
287 // when searching for the first non-date-line we have to take into account that our
288 // model still contains the just removed lines so we cannot simply call updateSceneRect()
289 int numRows = model()->rowCount();
290 QModelIndex firstLineIdx;
292 bool needOffset = false;
295 if(_firstLineRow >= start && _firstLineRow <= end) {
296 _firstLineRow = end + 1;
299 firstLineIdx = model()->index(_firstLineRow, 0);
300 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
303 _firstLineRow -= end - start + 1;
307 void ChatScene::updateForViewport(qreal width, qreal height) {
308 _viewportHeight = height;
312 void ChatScene::setWidth(qreal width) {
313 if(width == _sceneRect.width())
316 // clock_t startT = clock();
318 // disabling the index while doing this complex updates is about
319 // 2 to 10 times faster!
320 //setItemIndexMethod(QGraphicsScene::NoIndex);
322 QList<ChatLine *>::iterator lineIter = _lines.end();
323 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
324 qreal linePos = _sceneRect.y() + _sceneRect.height();
325 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
326 while(lineIter != lineIterBegin) {
328 (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
330 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
332 updateSceneRect(width);
335 // clock_t endT = clock();
336 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
339 void ChatScene::firstHandlePositionChanged(qreal xpos) {
340 if(_firstColHandlePos == xpos)
343 _firstColHandlePos = xpos;
344 ChatViewSettings viewSettings(this);
345 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
346 ChatViewSettings defaultSettings;
347 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
349 // clock_t startT = clock();
351 // disabling the index while doing this complex updates is about
352 // 2 to 10 times faster!
353 //setItemIndexMethod(QGraphicsScene::NoIndex);
355 QList<ChatLine *>::iterator lineIter = _lines.end();
356 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
357 qreal timestampWidth = firstColumnHandle()->sceneLeft();
358 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
359 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
361 while(lineIter != lineIterBegin) {
363 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
365 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
369 // clock_t endT = clock();
370 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
373 void ChatScene::secondHandlePositionChanged(qreal xpos) {
374 if(_secondColHandlePos == xpos)
377 _secondColHandlePos = xpos;
378 ChatViewSettings viewSettings(this);
379 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
380 ChatViewSettings defaultSettings;
381 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
383 // clock_t startT = clock();
385 // disabling the index while doing this complex updates is about
386 // 2 to 10 times faster!
387 //setItemIndexMethod(QGraphicsScene::NoIndex);
389 QList<ChatLine *>::iterator lineIter = _lines.end();
390 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
391 qreal linePos = _sceneRect.y() + _sceneRect.height();
392 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
393 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
394 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
395 while(lineIter != lineIterBegin) {
397 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
399 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
403 // clock_t endT = clock();
404 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
407 void ChatScene::setHandleXLimits() {
408 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
409 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
412 void ChatScene::setSelectingItem(ChatItem *item) {
413 if(_selectingItem) _selectingItem->clearSelection();
414 _selectingItem = item;
417 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
418 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
419 _selectionStartCol = _selectionMinCol = item->column();
421 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
422 updateSelection(item->mapToScene(itemPos));
425 void ChatScene::updateSelection(const QPointF &pos) {
426 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
427 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
428 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, pos.y())));
429 if(!contentItem) return;
431 int curRow = contentItem->row();
433 if(pos.x() > _secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
434 else if(pos.x() > _firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
435 else curColumn = ChatLineModel::TimestampColumn;
437 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
438 if(minColumn != _selectionMinCol) {
439 _selectionMinCol = minColumn;
440 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
441 _lines[l]->setSelected(true, minColumn);
444 int newstart = qMin(curRow, _firstSelectionRow);
445 int newend = qMax(curRow, _firstSelectionRow);
446 if(newstart < _selectionStart) {
447 for(int l = newstart; l < _selectionStart; l++)
448 _lines[l]->setSelected(true, minColumn);
450 if(newstart > _selectionStart) {
451 for(int l = _selectionStart; l < newstart; l++)
452 _lines[l]->setSelected(false);
454 if(newend > _selectionEnd) {
455 for(int l = _selectionEnd+1; l <= newend; l++)
456 _lines[l]->setSelected(true, minColumn);
458 if(newend < _selectionEnd) {
459 for(int l = newend+1; l <= _selectionEnd; l++)
460 _lines[l]->setSelected(false);
463 _selectionStart = newstart;
464 _selectionEnd = newend;
465 _lastSelectionRow = curRow;
467 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
468 if(!_selectingItem) {
469 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
472 _lines[curRow]->setSelected(false);
473 _isSelecting = false;
474 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
478 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
479 if(_isSelecting && event->buttons() == Qt::LeftButton) {
480 updateSelection(event->scenePos());
483 QGraphicsScene::mouseMoveEvent(event);
487 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
488 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
489 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
490 _lines[l]->setSelected(false);
492 _selectionStart = -1;
493 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
495 QGraphicsScene::mousePressEvent(event);
499 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
500 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
501 putToClipboard(selectionToString());
502 _isSelecting = false;
505 QGraphicsScene::mouseReleaseEvent(event);
509 void ChatScene::putToClipboard(const QString &selection) {
510 // TODO Configure clipboards
512 QApplication::clipboard()->setText(selection, QClipboard::Selection);
515 QApplication::clipboard()->setText(selection);
519 //!\brief Convert current selection to human-readable string.
520 QString ChatScene::selectionToString() const {
521 //TODO Make selection format configurable!
522 if(!_isSelecting) return QString();
523 int start = qMin(_selectionStart, _selectionEnd);
524 int end = qMax(_selectionStart, _selectionEnd);
525 if(start < 0 || end >= _lines.count()) {
526 qDebug() << "Invalid selection range:" << start << end;
530 for(int l = start; l <= end; l++) {
531 if(_selectionMinCol == ChatLineModel::TimestampColumn)
532 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
533 if(_selectionMinCol <= ChatLineModel::SenderColumn)
534 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
535 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
540 void ChatScene::requestBacklog() {
541 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
543 return filter->requestBacklog();
547 int ChatScene::sectionByScenePos(int x) {
548 if(x < _firstColHandle->x())
549 return ChatLineModel::TimestampColumn;
550 if(x < _secondColHandle->x())
551 return ChatLineModel::SenderColumn;
553 return ChatLineModel::ContentsColumn;
556 void ChatScene::updateSceneRect(qreal width) {
557 if(_lines.isEmpty()) {
558 updateSceneRect(QRectF(0, 0, width, 0));
562 // we hide day change messages at the top by making the scene rect smaller
563 // and by calling QGraphicsItem::hide() on all leading day change messages
564 // the first one is needed to ensure proper scrollbar ranges
565 // the second for cases where the viewport is larger then the set scenerect
566 // (in this case the items are shown anyways)
567 if(_firstLineRow == -1) {
568 int numRows = model()->rowCount();
570 QModelIndex firstLineIdx;
571 while(_firstLineRow < numRows) {
572 firstLineIdx = model()->index(_firstLineRow, 0);
573 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
575 _lines.at(_firstLineRow)->hide();
580 // the following call should be safe. If it crashes something went wrong during insert/remove
581 if(_firstLineRow < _lines.count()) {
582 ChatLine *firstLine = _lines.at(_firstLineRow);
583 ChatLine *lastLine = _lines.last();
584 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
587 updateSceneRect(QRectF(0, 0, width, 0));
591 void ChatScene::updateSceneRect(const QRectF &rect) {
597 bool ChatScene::event(QEvent *e) {
598 if(e->type() == QEvent::ApplicationPaletteChange) {
599 _firstColHandle->setColor(QApplication::palette().windowText().color());
600 _secondColHandle->setColor(QApplication::palette().windowText().color());
602 return QGraphicsScene::event(e);
605 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
611 if(webPreview.parentItem != parentItem)
612 webPreview.parentItem = parentItem;
614 if(webPreview.url != url) {
615 webPreview.url = url;
616 // load a new web view and delete the old one (if exists)
617 if(webPreview.previewItem && webPreview.previewItem->scene()) {
618 removeItem(webPreview.previewItem);
619 delete webPreview.previewItem;
621 webPreview.previewItem = new WebPreviewItem(url);
622 webPreview.delayTimer.start(2000);
623 webPreview.deleteTimer.stop();
624 } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
625 // we just have to readd the item to the scene
626 webPreview.delayTimer.start(2000);
627 webPreview.deleteTimer.stop();
629 if(webPreview.urlRect != urlRect) {
630 webPreview.urlRect = urlRect;
631 qreal previewY = urlRect.bottom();
632 qreal previewX = urlRect.x();
633 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
634 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
636 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
637 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
639 webPreview.previewItem->setPos(previewX, previewY);
644 void ChatScene::showWebPreviewEvent() {
646 if(webPreview.previewItem)
647 addItem(webPreview.previewItem);
651 void ChatScene::clearWebPreview(ChatItem *parentItem) {
655 if(parentItem == 0 || webPreview.parentItem == parentItem) {
656 if(webPreview.previewItem && webPreview.previewItem->scene()) {
657 removeItem(webPreview.previewItem);
658 webPreview.deleteTimer.start();
660 webPreview.delayTimer.stop();
665 void ChatScene::deleteWebPreviewEvent() {
667 if(webPreview.previewItem) {
668 delete webPreview.previewItem;
669 webPreview.previewItem = 0;
671 webPreview.parentItem = 0;
672 webPreview.url = QString();
673 webPreview.urlRect = QRectF();