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);
126 for(int i = end; i >= start; i--) {
127 ChatLine *line = new ChatLine(i, model(),
129 timestampWidth, senderWidth, contentsWidth,
130 senderPos, contentsPos);
132 line->setPos(0, y-h);
133 _lines.insert(start, line);
137 for(int i = start; i <= end; i++) {
138 ChatLine *line = new ChatLine(i, model(),
140 timestampWidth, senderWidth, contentsWidth,
141 senderPos, contentsPos);
142 line->setPos(0, y+h);
144 _lines.insert(i, line);
149 // update existing items
150 for(int i = end+1; i < _lines.count(); i++) {
151 _lines[i]->setRow(i);
155 if(_selectionStart >= 0) {
156 int offset = end - start + 1;
157 if(_selectionStart >= start) _selectionStart += offset;
158 if(_selectionEnd >= start) _selectionEnd += offset;
159 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
160 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
163 // neither pre- or append means we have to do dirty work: move items...
164 if(!(atTop || atBottom)) {
167 int moveEnd = _lines.count() - 1;
168 // move top means: moving 0 to end (aka: end + 1)
169 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
170 if(end + 1 < _lines.count() - end - 1) {
180 for(int i = moveStart; i <= moveEnd; i++) {
182 line->setPos(0, line->pos().y() + offset);
187 if(start < _firstLineRow) {
188 int prevFirstLineRow = _firstLineRow + (end - start + 1);
189 for(int i = end + 1; i < prevFirstLineRow; i++) {
190 _lines.at(i)->show();
193 // force new search for first proper line
198 emit lastLineChanged(_lines.last());
203 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
208 qreal h = 0; // total height of removed items;
210 bool atTop = (start == 0);
211 bool atBottom = (end == _lines.count() - 1);
212 bool moveTop = false;
214 // remove items from scene
215 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
216 int lineCount = start;
217 while(lineIter != _lines.end() && lineCount <= end) {
218 h += (*lineIter)->height();
220 lineIter = _lines.erase(lineIter);
224 // update rows of remaining chatlines
225 for(int i = start; i < _lines.count(); i++) {
226 _lines.at(i)->setRow(i);
230 if(_selectionStart >= 0) {
231 int offset = end - start + 1;
232 if(_selectionStart >= start)
233 _selectionStart -= offset;
234 if(_selectionEnd >= start)
235 _selectionEnd -= offset;
236 if(_firstSelectionRow >= start)
237 _firstSelectionRow -= offset;
238 if(_lastSelectionRow >= start)
239 _lastSelectionRow -= offset;
242 // neither removing at bottom or top means we have to move items...
243 if(!(atTop || atBottom)) {
246 int moveEnd = _lines.count() - 1;
247 if(start < _lines.count() - start) {
257 for(int i = moveStart; i <= moveEnd; i++) {
259 line->setPos(0, line->pos().y() + offset);
265 // when searching for the first non-date-line we have to take into account that our
266 // model still contains the just removed lines so we cannot simply call updateSceneRect()
267 int numRows = model()->rowCount();
268 QModelIndex firstLineIdx;
270 bool needOffset = false;
273 if(_firstLineRow >= start && _firstLineRow <= end) {
274 _firstLineRow = end + 1;
277 firstLineIdx = model()->index(_firstLineRow, 0);
278 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
281 _firstLineRow -= end - start + 1;
285 void ChatScene::updateForViewport(qreal width, qreal height) {
286 _viewportHeight = height;
290 // setWidth is used for 2 things:
291 // a) updating the scene to fit the width of the corresponding view
292 // b) to update the positions of the items if a columhandle has changed it's position
293 // forceReposition is true in the second case
294 // this method features some codeduplication for the sake of performance
295 void ChatScene::setWidth(qreal width, bool forceReposition) {
296 if(width == _sceneRect.width() && !forceReposition)
299 // clock_t startT = clock();
301 qreal linePos = _sceneRect.y() + _sceneRect.height();
302 QList<ChatLine *>::iterator lineIter = _lines.end();
303 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
305 qreal lineHeight = 0;
306 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
308 if(forceReposition) {
309 qreal timestampWidth = firstColumnHandle()->sceneLeft();
310 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
311 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
312 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
313 while(lineIter != lineIterBegin) {
316 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
317 linePos -= lineHeight;
318 line->setPos(0, linePos);
321 while(lineIter != lineIterBegin) {
324 lineHeight = line->setGeometryByWidth(width, contentsWidth);
325 linePos -= lineHeight;
326 line->setPos(0, linePos);
330 updateSceneRect(width);
333 // clock_t endT = clock();
334 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
337 void ChatScene::handlePositionChanged(qreal xpos) {
338 bool first = (sender() == firstColHandle);
341 oldx = firstColHandlePos;
342 firstColHandlePos = xpos;
344 oldx = secondColHandlePos;
345 secondColHandlePos = xpos;
348 ChatViewSettings viewSettings(this);
349 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
350 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
352 ChatViewSettings defaultSettings;
353 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
354 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
356 setWidth(width(), true); // readjust all chatlines
357 // we get ugly redraw errors if we don't update this explicitly... :(
358 // width() should be the same for both handles, so just use firstColHandle regardless
359 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
362 void ChatScene::setHandleXLimits() {
363 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
364 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
367 void ChatScene::setSelectingItem(ChatItem *item) {
368 if(_selectingItem) _selectingItem->clearSelection();
369 _selectingItem = item;
372 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
373 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
374 _selectionStartCol = _selectionMinCol = item->column();
376 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
377 updateSelection(item->mapToScene(itemPos));
380 void ChatScene::updateSelection(const QPointF &pos) {
381 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
382 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
383 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
384 if(!contentItem) return;
386 int curRow = contentItem->row();
388 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
389 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
390 else curColumn = ChatLineModel::TimestampColumn;
392 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
393 if(minColumn != _selectionMinCol) {
394 _selectionMinCol = minColumn;
395 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
396 _lines[l]->setSelected(true, minColumn);
399 int newstart = qMin(curRow, _firstSelectionRow);
400 int newend = qMax(curRow, _firstSelectionRow);
401 if(newstart < _selectionStart) {
402 for(int l = newstart; l < _selectionStart; l++)
403 _lines[l]->setSelected(true, minColumn);
405 if(newstart > _selectionStart) {
406 for(int l = _selectionStart; l < newstart; l++)
407 _lines[l]->setSelected(false);
409 if(newend > _selectionEnd) {
410 for(int l = _selectionEnd+1; l <= newend; l++)
411 _lines[l]->setSelected(true, minColumn);
413 if(newend < _selectionEnd) {
414 for(int l = newend+1; l <= _selectionEnd; l++)
415 _lines[l]->setSelected(false);
418 _selectionStart = newstart;
419 _selectionEnd = newend;
420 _lastSelectionRow = curRow;
422 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
423 if(!_selectingItem) {
424 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
427 _lines[curRow]->setSelected(false);
428 _isSelecting = false;
429 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
433 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
434 if(_isSelecting && event->buttons() == Qt::LeftButton) {
435 updateSelection(event->scenePos());
438 QGraphicsScene::mouseMoveEvent(event);
442 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
443 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
444 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
445 _lines[l]->setSelected(false);
447 _selectionStart = -1;
448 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
450 QGraphicsScene::mousePressEvent(event);
454 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
455 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
456 putToClipboard(selectionToString());
457 _isSelecting = false;
460 QGraphicsScene::mouseReleaseEvent(event);
464 void ChatScene::putToClipboard(const QString &selection) {
465 // TODO Configure clipboards
467 QApplication::clipboard()->setText(selection, QClipboard::Selection);
470 QApplication::clipboard()->setText(selection);
474 //!\brief Convert current selection to human-readable string.
475 QString ChatScene::selectionToString() const {
476 //TODO Make selection format configurable!
477 if(!_isSelecting) return QString();
478 int start = qMin(_selectionStart, _selectionEnd);
479 int end = qMax(_selectionStart, _selectionEnd);
480 if(start < 0 || end >= _lines.count()) {
481 qDebug() << "Invalid selection range:" << start << end;
485 for(int l = start; l <= end; l++) {
486 if(_selectionMinCol == ChatLineModel::TimestampColumn)
487 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
488 if(_selectionMinCol <= ChatLineModel::SenderColumn)
489 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
490 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
495 void ChatScene::requestBacklog() {
496 static const int REQUEST_COUNT = 500;
497 int backlogSize = model()->rowCount();
498 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
499 QModelIndex msgIdx = model()->index(0, 0);
500 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
501 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
503 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
504 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
505 _lastBacklogSize = backlogSize;
506 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
510 int ChatScene::sectionByScenePos(int x) {
511 if(x < firstColHandle->x())
512 return ChatLineModel::TimestampColumn;
513 if(x < secondColHandle->x())
514 return ChatLineModel::SenderColumn;
516 return ChatLineModel::ContentsColumn;
519 void ChatScene::updateSceneRect() {
520 if(_lines.isEmpty()) {
521 updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
525 // we hide day change messages at the top by making the scene rect smaller
526 // and by calling QGraphicsItem::hide() on all leading day change messages
527 // the first one is needed to ensure proper scrollbar ranges
528 // the second for cases where the viewport is larger then the set scenerect
529 // (in this case the items are shown anyways)
530 if(_firstLineRow == -1) {
531 int numRows = model()->rowCount();
533 QModelIndex firstLineIdx;
534 while(_firstLineRow < numRows) {
535 firstLineIdx = model()->index(_firstLineRow, 0);
536 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
538 _lines.at(_firstLineRow)->hide();
543 // the following call should be safe. If it crashes something went wrong during insert/remove
544 ChatLine *firstLine = _lines.at(_firstLineRow);
545 ChatLine *lastLine = _lines.last();
546 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
549 void ChatScene::updateSceneRect(qreal width) {
550 _sceneRect.setWidth(width);
554 void ChatScene::updateSceneRect(const QRectF &rect) {
560 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
566 if(webPreview.parentItem != parentItem)
567 webPreview.parentItem = parentItem;
569 if(webPreview.url != url) {
570 webPreview.url = url;
571 // load a new web view and delete the old one (if exists)
572 if(webPreview.previewItem) {
573 removeItem(webPreview.previewItem);
574 delete webPreview.previewItem;
576 webPreview.previewItem = new WebPreviewItem(url);
577 addItem(webPreview.previewItem);
579 if(webPreview.urlRect != urlRect) {
580 webPreview.urlRect = urlRect;
581 qreal previewY = urlRect.bottom();
582 qreal previewX = urlRect.x();
583 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
584 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
586 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
587 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
589 webPreview.previewItem->setPos(previewX, previewY);
594 void ChatScene::clearWebPreview(ChatItem *parentItem) {
598 if(parentItem == 0 || webPreview.parentItem == parentItem) {
599 if(webPreview.previewItem) {
600 removeItem(webPreview.previewItem);
601 delete webPreview.previewItem;
602 webPreview.previewItem = 0;
604 webPreview.parentItem = 0;
605 webPreview.url = QString();
606 webPreview.urlRect = QRectF();