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 if(start < _firstLineRow) {
180 int prevFirstLineRow = _firstLineRow + (end - start + 1);
181 for(int i = end + 1; i < prevFirstLineRow; i++) {
182 _lines.at(i)->show();
185 // force new search for first proper line
190 emit lastLineChanged(_lines.last());
195 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
200 qreal h = 0; // total height of removed items;
202 bool atTop = (start == 0);
203 bool atBottom = (end == _lines.count() - 1);
204 bool moveTop = false;
206 // remove items from scene
207 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
208 int lineCount = start;
209 while(lineIter != _lines.end() && lineCount <= end) {
210 h += (*lineIter)->height();
212 lineIter = _lines.erase(lineIter);
216 // update rows of remaining chatlines
217 for(int i = start; i < _lines.count(); i++) {
218 _lines.at(i)->setRow(i);
222 if(_selectionStart >= 0) {
223 int offset = end - start + 1;
224 if(_selectionStart >= start)
225 _selectionStart -= offset;
226 if(_selectionEnd >= start)
227 _selectionEnd -= offset;
228 if(_firstSelectionRow >= start)
229 _firstSelectionRow -= offset;
230 if(_lastSelectionRow >= start)
231 _lastSelectionRow -= offset;
234 // neither removing at bottom or top means we have to move items...
235 if(!(atTop || atBottom)) {
238 int moveEnd = _lines.count() - 1;
239 if(start < _lines.count() - start) {
249 for(int i = moveStart; i <= moveEnd; i++) {
251 line->setPos(0, line->pos().y() + offset);
257 // when searching for the first non-date-line we have to take into account that our
258 // model still contains the just removed lines so we cannot simply call updateSceneRect()
259 int numRows = model()->rowCount();
260 QModelIndex firstLineIdx;
262 bool needOffset = false;
265 if(_firstLineRow >= start && _firstLineRow <= end) {
266 _firstLineRow = end + 1;
269 firstLineIdx = model()->index(_firstLineRow, 0);
270 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
273 _firstLineRow -= end - start + 1;
277 void ChatScene::updateForViewport(qreal width, qreal height) {
278 _viewportHeight = height;
282 // setWidth is used for 2 things:
283 // a) updating the scene to fit the width of the corresponding view
284 // b) to update the positions of the items if a columhandle has changed it's position
285 // forceReposition is true in the second case
286 // this method features some codeduplication for the sake of performance
287 void ChatScene::setWidth(qreal width, bool forceReposition) {
288 if(width == _sceneRect.width() && !forceReposition)
291 // clock_t startT = clock();
293 qreal linePos = _sceneRect.y() + _sceneRect.height();
294 QList<ChatLine *>::iterator lineIter = _lines.end();
295 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
297 qreal lineHeight = 0;
298 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
300 if(forceReposition) {
301 qreal timestampWidth = firstColumnHandle()->sceneLeft();
302 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
303 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
304 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
305 while(lineIter != lineIterBegin) {
308 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
309 linePos -= lineHeight;
310 line->setPos(0, linePos);
313 while(lineIter != lineIterBegin) {
316 lineHeight = line->setGeometryByWidth(width, contentsWidth);
317 linePos -= lineHeight;
318 line->setPos(0, linePos);
322 updateSceneRect(width);
325 // clock_t endT = clock();
326 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
329 void ChatScene::handlePositionChanged(qreal xpos) {
330 bool first = (sender() == firstColHandle);
333 oldx = firstColHandlePos;
334 firstColHandlePos = xpos;
336 oldx = secondColHandlePos;
337 secondColHandlePos = xpos;
340 ChatViewSettings viewSettings(this);
341 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
342 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
344 ChatViewSettings defaultSettings;
345 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
346 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
348 setWidth(width(), true); // readjust all chatlines
349 // we get ugly redraw errors if we don't update this explicitly... :(
350 // width() should be the same for both handles, so just use firstColHandle regardless
351 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
354 void ChatScene::setHandleXLimits() {
355 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
356 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
359 void ChatScene::setSelectingItem(ChatItem *item) {
360 if(_selectingItem) _selectingItem->clearSelection();
361 _selectingItem = item;
364 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
365 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
366 _selectionStartCol = _selectionMinCol = item->column();
368 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
369 updateSelection(item->mapToScene(itemPos));
372 void ChatScene::updateSelection(const QPointF &pos) {
373 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
374 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
375 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
376 if(!contentItem) return;
378 int curRow = contentItem->row();
380 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
381 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
382 else curColumn = ChatLineModel::TimestampColumn;
384 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
385 if(minColumn != _selectionMinCol) {
386 _selectionMinCol = minColumn;
387 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
388 _lines[l]->setSelected(true, minColumn);
391 int newstart = qMin(curRow, _firstSelectionRow);
392 int newend = qMax(curRow, _firstSelectionRow);
393 if(newstart < _selectionStart) {
394 for(int l = newstart; l < _selectionStart; l++)
395 _lines[l]->setSelected(true, minColumn);
397 if(newstart > _selectionStart) {
398 for(int l = _selectionStart; l < newstart; l++)
399 _lines[l]->setSelected(false);
401 if(newend > _selectionEnd) {
402 for(int l = _selectionEnd+1; l <= newend; l++)
403 _lines[l]->setSelected(true, minColumn);
405 if(newend < _selectionEnd) {
406 for(int l = newend+1; l <= _selectionEnd; l++)
407 _lines[l]->setSelected(false);
410 _selectionStart = newstart;
411 _selectionEnd = newend;
412 _lastSelectionRow = curRow;
414 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
415 if(!_selectingItem) {
416 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
419 _lines[curRow]->setSelected(false);
420 _isSelecting = false;
421 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
425 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
426 if(_isSelecting && event->buttons() == Qt::LeftButton) {
427 updateSelection(event->scenePos());
430 QGraphicsScene::mouseMoveEvent(event);
434 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
435 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
436 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
437 _lines[l]->setSelected(false);
439 _selectionStart = -1;
440 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
442 QGraphicsScene::mousePressEvent(event);
446 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
447 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
448 putToClipboard(selectionToString());
449 _isSelecting = false;
452 QGraphicsScene::mouseReleaseEvent(event);
456 void ChatScene::putToClipboard(const QString &selection) {
457 // TODO Configure clipboards
459 QApplication::clipboard()->setText(selection, QClipboard::Selection);
462 QApplication::clipboard()->setText(selection);
466 //!\brief Convert current selection to human-readable string.
467 QString ChatScene::selectionToString() const {
468 //TODO Make selection format configurable!
469 if(!_isSelecting) return QString();
470 int start = qMin(_selectionStart, _selectionEnd);
471 int end = qMax(_selectionStart, _selectionEnd);
472 if(start < 0 || end >= _lines.count()) {
473 qDebug() << "Invalid selection range:" << start << end;
477 for(int l = start; l <= end; l++) {
478 if(_selectionMinCol == ChatLineModel::TimestampColumn)
479 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
480 if(_selectionMinCol <= ChatLineModel::SenderColumn)
481 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
482 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
487 void ChatScene::requestBacklog() {
488 static const int REQUEST_COUNT = 500;
489 int backlogSize = model()->rowCount();
490 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
491 QModelIndex msgIdx = model()->index(0, 0);
492 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
493 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
495 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
496 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
497 _lastBacklogSize = backlogSize;
498 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
502 int ChatScene::sectionByScenePos(int x) {
503 if(x < firstColHandle->x())
504 return ChatLineModel::TimestampColumn;
505 if(x < secondColHandle->x())
506 return ChatLineModel::SenderColumn;
508 return ChatLineModel::ContentsColumn;
511 void ChatScene::updateSceneRect() {
512 if(_lines.isEmpty()) {
513 updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
517 // we hide day change messages at the top by making the scene rect smaller
518 // and by calling QGraphicsItem::hide() on all leading day change messages
519 // the first one is needed to ensure proper scrollbar ranges
520 // the second for cases where the viewport is larger then the set scenerect
521 // (in this case the items are shown anyways)
522 if(_firstLineRow == -1) {
523 int numRows = model()->rowCount();
525 QModelIndex firstLineIdx;
526 while(_firstLineRow < numRows) {
527 firstLineIdx = model()->index(_firstLineRow, 0);
528 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
530 _lines.at(_firstLineRow)->hide();
535 // the following call should be safe. If it crashes something went wrong during insert/remove
536 ChatLine *firstLine = _lines.at(_firstLineRow);
537 ChatLine *lastLine = _lines.last();
538 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
541 void ChatScene::updateSceneRect(qreal width) {
542 _sceneRect.setWidth(width);
546 void ChatScene::updateSceneRect(const QRectF &rect) {
552 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
558 if(webPreview.parentItem != parentItem)
559 webPreview.parentItem = parentItem;
561 if(webPreview.url != url) {
562 webPreview.url = url;
563 // load a new web view and delete the old one (if exists)
564 if(webPreview.previewItem) {
565 removeItem(webPreview.previewItem);
566 delete webPreview.previewItem;
568 webPreview.previewItem = new WebPreviewItem(url);
569 addItem(webPreview.previewItem);
571 if(webPreview.urlRect != urlRect) {
572 webPreview.urlRect = urlRect;
573 qreal previewY = urlRect.bottom();
574 qreal previewX = urlRect.x();
575 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
576 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
578 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
579 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
581 webPreview.previewItem->setPos(previewX, previewY);
586 void ChatScene::clearWebPreview(ChatItem *parentItem) {
590 if(parentItem == 0 || webPreview.parentItem == parentItem) {
591 if(webPreview.previewItem) {
592 removeItem(webPreview.previewItem);
593 delete webPreview.previewItem;
594 webPreview.previewItem = 0;
596 webPreview.parentItem = 0;
597 webPreview.url = QString();
598 webPreview.urlRect = QRectF();