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>
28 #include "chatlinemodelitem.h"
29 #include "chatscene.h"
31 #include "clientbacklogmanager.h"
32 #include "columnhandleitem.h"
33 #include "messagefilter.h"
35 #include "qtuistyle.h"
36 #include "chatviewsettings.h"
37 #include "webpreviewitem.h"
39 const qreal minContentsWidth = 200;
41 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
42 : QGraphicsScene(0, 0, width, 0, parent),
45 _singleBufferScene(false),
46 _sceneRect(0, 0, width, 0),
54 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
56 _singleBufferScene = filter->isSingleBufferFilter();
59 ChatViewSettings defaultSettings;
60 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
61 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
63 ChatViewSettings viewSettings(this);
64 firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
65 secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
67 firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
68 addItem(firstColHandle);
69 firstColHandle->setXPos(firstColHandlePos);
70 connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
71 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
73 secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
74 addItem(secondColHandle);
75 secondColHandle->setXPos(secondColHandlePos);
76 connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
77 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
81 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
82 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
83 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
84 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
86 if(model->rowCount() > 0)
87 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
90 ChatScene::~ChatScene() {
93 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
98 // QModelIndex sidx = model()->index(start, 0);
99 // QModelIndex eidx = model()->index(end, 0);
100 // qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
103 qreal y = _sceneRect.y();
104 qreal width = _sceneRect.width();
106 bool atBottom = false;
107 bool moveTop = false;
109 if(start > 0 && start < _lines.count()) {
110 y = _lines.value(start)->y();
113 if(start == _lines.count()) {
114 y = _sceneRect.bottom();
119 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
120 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
121 qreal timestampWidth = firstColumnHandle()->sceneLeft();
122 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
123 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
125 for(int i = start; i <= end; i++) {
126 ChatLine *line = new ChatLine(i, model(),
128 timestampWidth, senderWidth, contentsWidth,
129 senderPos, contentsPos);
132 line->setPos(0, y-h);
134 line->setPos(0, y+h);
137 _lines.insert(i, line);
141 // update existing items
142 for(int i = end+1; i < _lines.count(); i++) {
143 _lines[i]->setRow(i);
147 if(_selectionStart >= 0) {
148 int offset = end - start + 1;
149 if(_selectionStart >= start) _selectionStart += offset;
150 if(_selectionEnd >= start) _selectionEnd += offset;
151 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
152 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
155 // neither pre- or append means we have to do dirty work: move items...
156 if(!(atTop || atBottom)) {
159 int moveEnd = _lines.count() - 1;
160 // move top means: moving 0 to end (aka: end + 1)
161 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
162 if(end + 1 < _lines.count() - end - 1) {
172 for(int i = moveStart; i <= moveEnd; i++) {
174 line->setPos(0, line->pos().y() + offset);
179 // force new search for first proper line
184 emit lastLineChanged(_lines.last());
189 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
194 qreal h = 0; // total height of removed items;
196 bool atTop = (start == 0);
197 bool atBottom = (end == _lines.count() - 1);
198 bool moveTop = false;
200 // remove items from scene
201 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
202 int lineCount = start;
203 while(lineIter != _lines.end() && lineCount <= end) {
204 h += (*lineIter)->height();
206 lineIter = _lines.erase(lineIter);
210 // update rows of remaining chatlines
211 for(int i = start; i < _lines.count(); i++) {
212 _lines.at(i)->setRow(i);
216 if(_selectionStart >= 0) {
217 int offset = end - start + 1;
218 if(_selectionStart >= start)
219 _selectionStart -= offset;
220 if(_selectionEnd >= start)
221 _selectionEnd -= offset;
222 if(_firstSelectionRow >= start)
223 _firstSelectionRow -= offset;
224 if(_lastSelectionRow >= start)
225 _lastSelectionRow -= offset;
228 // neither removing at bottom or top means we have to move items...
229 if(!(atTop || atBottom)) {
232 int moveEnd = _lines.count() - 1;
233 if(start < _lines.count() - start) {
243 for(int i = moveStart; i <= moveEnd; i++) {
245 line->setPos(0, line->pos().y() + offset);
251 // when searching for the first non-date-line we have to take into account that our
252 // model still contains the just removed lines so we cannot simply call updateSceneRect()
253 int numRows = model()->rowCount();
254 QModelIndex firstLineIdx;
256 bool needOffset = false;
259 if(_firstLineRow >= start && _firstLineRow <= end) {
260 _firstLineRow = end + 1;
263 firstLineIdx = model()->index(_firstLineRow, 0);
264 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
267 _firstLineRow -= end - start + 1;
271 void ChatScene::updateForViewport(qreal width, qreal height) {
272 _viewportHeight = height;
276 // setWidth is used for 2 things:
277 // a) updating the scene to fit the width of the corresponding view
278 // b) to update the positions of the items if a columhandle has changed it's position
279 // forceReposition is true in the second case
280 // this method features some codeduplication for the sake of performance
281 void ChatScene::setWidth(qreal width, bool forceReposition) {
282 if(width == _sceneRect.width() && !forceReposition)
285 // clock_t startT = clock();
287 qreal linePos = _sceneRect.y() + _sceneRect.height();
288 QList<ChatLine *>::iterator lineIter = _lines.end();
289 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
291 qreal lineHeight = 0;
292 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
294 if(forceReposition) {
295 qreal timestampWidth = firstColumnHandle()->sceneLeft();
296 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
297 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
298 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
299 while(lineIter != lineIterBegin) {
302 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
303 linePos -= lineHeight;
304 line->setPos(0, linePos);
307 while(lineIter != lineIterBegin) {
310 lineHeight = line->setGeometryByWidth(width, contentsWidth);
311 linePos -= lineHeight;
312 line->setPos(0, linePos);
316 updateSceneRect(width);
319 // clock_t endT = clock();
320 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
323 void ChatScene::handlePositionChanged(qreal xpos) {
324 bool first = (sender() == firstColHandle);
327 oldx = firstColHandlePos;
328 firstColHandlePos = xpos;
330 oldx = secondColHandlePos;
331 secondColHandlePos = xpos;
334 ChatViewSettings viewSettings(this);
335 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
336 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
338 ChatViewSettings defaultSettings;
339 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
340 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
342 setWidth(width(), true); // readjust all chatlines
343 // we get ugly redraw errors if we don't update this explicitly... :(
344 // width() should be the same for both handles, so just use firstColHandle regardless
345 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
348 void ChatScene::setHandleXLimits() {
349 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
350 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
353 void ChatScene::setSelectingItem(ChatItem *item) {
354 if(_selectingItem) _selectingItem->clearSelection();
355 _selectingItem = item;
358 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
359 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
360 _selectionStartCol = _selectionMinCol = item->column();
362 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
363 updateSelection(item->mapToScene(itemPos));
366 void ChatScene::updateSelection(const QPointF &pos) {
367 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
368 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
369 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
370 if(!contentItem) return;
372 int curRow = contentItem->row();
374 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
375 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
376 else curColumn = ChatLineModel::TimestampColumn;
378 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
379 if(minColumn != _selectionMinCol) {
380 _selectionMinCol = minColumn;
381 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
382 _lines[l]->setSelected(true, minColumn);
385 int newstart = qMin(curRow, _firstSelectionRow);
386 int newend = qMax(curRow, _firstSelectionRow);
387 if(newstart < _selectionStart) {
388 for(int l = newstart; l < _selectionStart; l++)
389 _lines[l]->setSelected(true, minColumn);
391 if(newstart > _selectionStart) {
392 for(int l = _selectionStart; l < newstart; l++)
393 _lines[l]->setSelected(false);
395 if(newend > _selectionEnd) {
396 for(int l = _selectionEnd+1; l <= newend; l++)
397 _lines[l]->setSelected(true, minColumn);
399 if(newend < _selectionEnd) {
400 for(int l = newend+1; l <= _selectionEnd; l++)
401 _lines[l]->setSelected(false);
404 _selectionStart = newstart;
405 _selectionEnd = newend;
406 _lastSelectionRow = curRow;
408 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
409 if(!_selectingItem) {
410 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
413 _lines[curRow]->setSelected(false);
414 _isSelecting = false;
415 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
419 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
420 if(_isSelecting && event->buttons() == Qt::LeftButton) {
421 updateSelection(event->scenePos());
424 QGraphicsScene::mouseMoveEvent(event);
428 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
429 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
430 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
431 _lines[l]->setSelected(false);
433 _selectionStart = -1;
434 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
436 QGraphicsScene::mousePressEvent(event);
440 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
441 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
442 putToClipboard(selectionToString());
443 _isSelecting = false;
446 QGraphicsScene::mouseReleaseEvent(event);
450 void ChatScene::putToClipboard(const QString &selection) {
451 // TODO Configure clipboards
453 QApplication::clipboard()->setText(selection, QClipboard::Selection);
456 QApplication::clipboard()->setText(selection);
460 //!\brief Convert current selection to human-readable string.
461 QString ChatScene::selectionToString() const {
462 //TODO Make selection format configurable!
463 if(!_isSelecting) return QString();
464 int start = qMin(_selectionStart, _selectionEnd);
465 int end = qMax(_selectionStart, _selectionEnd);
466 if(start < 0 || end >= _lines.count()) {
467 qDebug() << "Invalid selection range:" << start << end;
471 for(int l = start; l <= end; l++) {
472 if(_selectionMinCol == ChatLineModel::TimestampColumn)
473 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
474 if(_selectionMinCol <= ChatLineModel::SenderColumn)
475 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
476 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
481 void ChatScene::requestBacklog() {
482 static const int REQUEST_COUNT = 500;
483 int backlogSize = model()->rowCount();
484 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
485 QModelIndex msgIdx = model()->index(0, 0);
486 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
487 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
489 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
490 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
491 _lastBacklogSize = backlogSize;
492 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
496 int ChatScene::sectionByScenePos(int x) {
497 if(x < firstColHandle->x())
498 return ChatLineModel::TimestampColumn;
499 if(x < secondColHandle->x())
500 return ChatLineModel::SenderColumn;
502 return ChatLineModel::ContentsColumn;
505 void ChatScene::updateSceneRect() {
506 if(_lines.isEmpty()) {
507 updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
511 // we hide day change messages at the top by making the scene rect smaller
512 if(_firstLineRow == -1) {
513 int numRows = model()->rowCount();
514 QModelIndex firstLineIdx;
517 firstLineIdx = model()->index(_firstLineRow, 0);
518 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
521 // the following call should be safe. If it crashes something went wrong during insert/remove
522 ChatLine *firstLine = _lines.at(_firstLineRow);
523 ChatLine *lastLine = _lines.last();
524 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
527 void ChatScene::updateSceneRect(qreal width) {
528 _sceneRect.setWidth(width);
532 void ChatScene::updateSceneRect(const QRectF &rect) {
538 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
544 if(webPreview.parentItem != parentItem)
545 webPreview.parentItem = parentItem;
547 if(webPreview.url != url) {
548 webPreview.url = url;
549 // load a new web view and delete the old one (if exists)
550 if(webPreview.previewItem) {
551 removeItem(webPreview.previewItem);
552 delete webPreview.previewItem;
554 webPreview.previewItem = new WebPreviewItem(url);
555 addItem(webPreview.previewItem);
557 if(webPreview.urlRect != urlRect) {
558 webPreview.urlRect = urlRect;
559 qreal previewY = urlRect.bottom();
560 qreal previewX = urlRect.x();
561 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
562 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
564 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
565 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
567 webPreview.previewItem->setPos(previewX, previewY);
572 void ChatScene::clearWebPreview(ChatItem *parentItem) {
576 if(parentItem == 0 || webPreview.parentItem == parentItem) {
577 if(webPreview.previewItem) {
578 removeItem(webPreview.previewItem);
579 delete webPreview.previewItem;
580 webPreview.previewItem = 0;
582 webPreview.parentItem = 0;
583 webPreview.url = QString();
584 webPreview.urlRect = QRectF();