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),
53 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
55 _singleBufferScene = filter->isSingleBufferFilter();
58 ChatViewSettings defaultSettings;
59 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
60 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
62 ChatViewSettings viewSettings(this);
63 firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
64 secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
66 firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
67 addItem(firstColHandle);
68 firstColHandle->setXPos(firstColHandlePos);
69 connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
70 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
72 secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
73 addItem(secondColHandle);
74 secondColHandle->setXPos(secondColHandlePos);
75 connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
76 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
80 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
81 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
82 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
83 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
85 if(model->rowCount() > 0)
86 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
89 ChatScene::~ChatScene() {
92 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
97 // QModelIndex sidx = model()->index(start, 0);
98 // QModelIndex eidx = model()->index(end, 0);
99 // qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
102 qreal y = _sceneRect.y();
103 qreal width = _sceneRect.width();
105 bool atBottom = false;
106 bool moveTop = false;
108 if(start > 0 && start < _lines.count()) {
109 y = _lines.value(start)->y();
112 if(start == _lines.count()) {
113 y = _sceneRect.bottom();
118 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
119 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
120 qreal timestampWidth = firstColumnHandle()->sceneLeft();
121 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
122 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
124 for(int i = start; i <= end; i++) {
125 ChatLine *line = new ChatLine(i, model(),
127 timestampWidth, senderWidth, contentsWidth,
128 senderPos, contentsPos);
129 line->setPos(0, y+h);
131 _lines.insert(i, line);
135 // update existing items
136 for(int i = end+1; i < _lines.count(); i++) {
137 _lines[i]->setRow(i);
141 if(_selectionStart >= 0) {
142 int offset = end - start + 1;
143 if(_selectionStart >= start) _selectionStart += offset;
144 if(_selectionEnd >= start) _selectionEnd += offset;
145 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
146 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
149 // neither pre- or append means we have to do dirty work: move items...
150 if(!(atTop || atBottom)) {
153 int moveEnd = _lines.count() - 1;
154 // move top means: moving 0 to end (aka: end + 1)
155 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
156 if(end + 1 < _lines.count() - end - 1) {
166 for(int i = moveStart; i <= moveEnd; i++) {
168 line->setPos(0, line->pos().y() + offset);
174 emit lastLineChanged(_lines.last());
179 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
184 qreal h = 0; // total height of removed items;
186 bool atTop = (start == 0);
187 bool atBottom = (end == _lines.count() - 1);
188 bool moveTop = false;
190 // remove items from scene
191 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
192 int lineCount = start;
193 while(lineIter != _lines.end() && lineCount <= end) {
194 h += (*lineIter)->height();
196 lineIter = _lines.erase(lineIter);
200 // update rows of remaining chatlines
201 for(int i = start; i < _lines.count(); i++) {
202 _lines.at(i)->setRow(i);
206 if(_selectionStart >= 0) {
207 int offset = end - start + 1;
208 if(_selectionStart >= start)
209 _selectionStart -= offset;
210 if(_selectionEnd >= start)
211 _selectionEnd -= offset;
212 if(_firstSelectionRow >= start)
213 _firstSelectionRow -= offset;
214 if(_lastSelectionRow >= start)
215 _lastSelectionRow -= offset;
218 // neither removing at bottom or top means we have to move items...
219 if(!(atTop || atBottom)) {
222 int moveEnd = _lines.count() - 1;
223 if(start < _lines.count() - start) {
233 for(int i = moveStart; i <= moveEnd; i++) {
235 line->setPos(0, line->pos().y() + offset);
241 // when searching for the first non-date-line we have to take into account that our
242 // model still contains the just removed lines so we cannot simply call updateSceneRect()
243 int numRows = model()->rowCount();
244 QModelIndex firstLineIdx;
246 bool needOffset = false;
249 if(row >= start && row <= end) {
253 firstLineIdx = model()->index(row, 0);
254 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && row < numRows);
257 row -= end - start + 1;
259 ChatLine *firstLine = _lines.at(row);
260 ChatLine *lastLine = _lines.last();
262 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
265 void ChatScene::updateForViewport(qreal width, qreal height) {
266 _viewportHeight = height;
270 // setWidth is used for 2 things:
271 // a) updating the scene to fit the width of the corresponding view
272 // b) to update the positions of the items if a columhandle has changed it's position
273 // forceReposition is true in the second case
274 // this method features some codeduplication for the sake of performance
275 void ChatScene::setWidth(qreal width, bool forceReposition) {
276 if(width == _sceneRect.width() && !forceReposition)
279 // clock_t startT = clock();
281 qreal linePos = _sceneRect.y() + _sceneRect.height();
282 QList<ChatLine *>::iterator lineIter = _lines.end();
283 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
285 qreal lineHeight = 0;
286 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
288 if(forceReposition) {
289 qreal timestampWidth = firstColumnHandle()->sceneLeft();
290 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
291 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
292 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
293 while(lineIter != lineIterBegin) {
296 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
297 linePos -= lineHeight;
298 line->setPos(0, linePos);
301 while(lineIter != lineIterBegin) {
304 lineHeight = line->setGeometryByWidth(width, contentsWidth);
305 linePos -= lineHeight;
306 line->setPos(0, linePos);
310 updateSceneRect(width);
313 // clock_t endT = clock();
314 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
317 void ChatScene::handlePositionChanged(qreal xpos) {
318 bool first = (sender() == firstColHandle);
321 oldx = firstColHandlePos;
322 firstColHandlePos = xpos;
324 oldx = secondColHandlePos;
325 secondColHandlePos = xpos;
328 ChatViewSettings viewSettings(this);
329 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
330 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
332 ChatViewSettings defaultSettings;
333 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
334 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
336 setWidth(width(), true); // readjust all chatlines
337 // we get ugly redraw errors if we don't update this explicitly... :(
338 // width() should be the same for both handles, so just use firstColHandle regardless
339 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
342 void ChatScene::setHandleXLimits() {
343 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
344 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
347 void ChatScene::setSelectingItem(ChatItem *item) {
348 if(_selectingItem) _selectingItem->clearSelection();
349 _selectingItem = item;
352 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
353 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
354 _selectionStartCol = _selectionMinCol = item->column();
356 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
357 updateSelection(item->mapToScene(itemPos));
360 void ChatScene::updateSelection(const QPointF &pos) {
361 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
362 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
363 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
364 if(!contentItem) return;
366 int curRow = contentItem->row();
368 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
369 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
370 else curColumn = ChatLineModel::TimestampColumn;
372 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
373 if(minColumn != _selectionMinCol) {
374 _selectionMinCol = minColumn;
375 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
376 _lines[l]->setSelected(true, minColumn);
379 int newstart = qMin(curRow, _firstSelectionRow);
380 int newend = qMax(curRow, _firstSelectionRow);
381 if(newstart < _selectionStart) {
382 for(int l = newstart; l < _selectionStart; l++)
383 _lines[l]->setSelected(true, minColumn);
385 if(newstart > _selectionStart) {
386 for(int l = _selectionStart; l < newstart; l++)
387 _lines[l]->setSelected(false);
389 if(newend > _selectionEnd) {
390 for(int l = _selectionEnd+1; l <= newend; l++)
391 _lines[l]->setSelected(true, minColumn);
393 if(newend < _selectionEnd) {
394 for(int l = newend+1; l <= _selectionEnd; l++)
395 _lines[l]->setSelected(false);
398 _selectionStart = newstart;
399 _selectionEnd = newend;
400 _lastSelectionRow = curRow;
402 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
403 if(!_selectingItem) {
404 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
407 _lines[curRow]->setSelected(false);
408 _isSelecting = false;
409 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
413 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
414 if(_isSelecting && event->buttons() == Qt::LeftButton) {
415 updateSelection(event->scenePos());
418 QGraphicsScene::mouseMoveEvent(event);
422 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
423 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
424 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
425 _lines[l]->setSelected(false);
427 _selectionStart = -1;
428 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
430 QGraphicsScene::mousePressEvent(event);
434 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
435 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
436 putToClipboard(selectionToString());
437 _isSelecting = false;
440 QGraphicsScene::mouseReleaseEvent(event);
444 void ChatScene::putToClipboard(const QString &selection) {
445 // TODO Configure clipboards
447 QApplication::clipboard()->setText(selection, QClipboard::Selection);
450 QApplication::clipboard()->setText(selection);
454 //!\brief Convert current selection to human-readable string.
455 QString ChatScene::selectionToString() const {
456 //TODO Make selection format configurable!
457 if(!_isSelecting) return QString();
458 int start = qMin(_selectionStart, _selectionEnd);
459 int end = qMax(_selectionStart, _selectionEnd);
460 if(start < 0 || end >= _lines.count()) {
461 qDebug() << "Invalid selection range:" << start << end;
465 for(int l = start; l <= end; l++) {
466 if(_selectionMinCol == ChatLineModel::TimestampColumn)
467 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
468 if(_selectionMinCol <= ChatLineModel::SenderColumn)
469 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
470 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
475 void ChatScene::requestBacklog() {
476 static const int REQUEST_COUNT = 500;
477 int backlogSize = model()->rowCount();
478 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
479 QModelIndex msgIdx = model()->index(0, 0);
480 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
481 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
483 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
484 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
485 _lastBacklogSize = backlogSize;
486 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
490 int ChatScene::sectionByScenePos(int x) {
491 if(x < firstColHandle->x())
492 return ChatLineModel::TimestampColumn;
493 if(x < secondColHandle->x())
494 return ChatLineModel::SenderColumn;
496 return ChatLineModel::ContentsColumn;
499 void ChatScene::updateSceneRect() {
503 // we hide day change messages at the top by making the scene rect smaller
504 int numRows = model()->rowCount();
506 QModelIndex firstLineIdx;
509 firstLineIdx = model()->index(row, 0);
510 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && row < numRows);
512 // the following call should be safe. If it crashes something went wrong during insert/remove
513 ChatLine *firstLine = _lines.at(row);
514 ChatLine *lastLine = _lines.last();
516 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
519 void ChatScene::updateSceneRect(qreal width) {
520 _sceneRect.setWidth(width);
524 void ChatScene::updateSceneRect(const QRectF &rect) {
530 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
536 if(webPreview.parentItem != parentItem)
537 webPreview.parentItem = parentItem;
539 if(webPreview.url != url) {
540 webPreview.url = url;
541 // load a new web view and delete the old one (if exists)
542 if(webPreview.previewItem) {
543 removeItem(webPreview.previewItem);
544 delete webPreview.previewItem;
546 webPreview.previewItem = new WebPreviewItem(url);
547 addItem(webPreview.previewItem);
549 if(webPreview.urlRect != urlRect) {
550 webPreview.urlRect = urlRect;
551 qreal previewY = urlRect.bottom();
552 qreal previewX = urlRect.x();
553 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
554 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
556 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
557 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
559 webPreview.previewItem->setPos(previewX, previewY);
564 void ChatScene::clearWebPreview(ChatItem *parentItem) {
568 if(parentItem == 0 || webPreview.parentItem == parentItem) {
569 if(webPreview.previewItem) {
570 removeItem(webPreview.previewItem);
571 delete webPreview.previewItem;
572 webPreview.previewItem = 0;
574 webPreview.parentItem = 0;
575 webPreview.url = QString();
576 webPreview.urlRect = QRectF();