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 class ChatScene::ClearWebPreviewEvent : public QEvent {
44 inline ClearWebPreviewEvent() : QEvent((QEvent::Type)ChatScene::ClearWebPreviewEventType) {}
47 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
48 : QGraphicsScene(0, 0, width, 0, parent),
51 _singleBufferScene(false),
52 _sceneRect(0, 0, width, 0),
60 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
62 _singleBufferScene = filter->isSingleBufferFilter();
65 ChatViewSettings defaultSettings;
66 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
67 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
69 ChatViewSettings viewSettings(this);
70 firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
71 secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
73 firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
74 addItem(firstColHandle);
75 firstColHandle->setXPos(firstColHandlePos);
76 connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
77 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
79 secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
80 addItem(secondColHandle);
81 secondColHandle->setXPos(secondColHandlePos);
82 connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
83 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
87 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
88 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
89 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
90 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
92 if(model->rowCount() > 0)
93 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
95 webPreview.delayTimer.setSingleShot(true);
96 connect(&webPreview.delayTimer, SIGNAL(timeout()), this, SLOT(showWebPreview()));
98 // installEventFilter(this);
99 setItemIndexMethod(QGraphicsScene::NoIndex);
102 ChatScene::~ChatScene() {
105 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
107 // QModelIndex sidx = model()->index(start, 0);
108 // QModelIndex eidx = model()->index(end, 0);
109 // qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
112 qreal y = _sceneRect.y();
113 qreal width = _sceneRect.width();
115 bool atBottom = false;
116 bool moveTop = false;
118 if(start > 0 && start < _lines.count()) {
119 y = _lines.value(start)->y();
122 if(start == _lines.count()) {
123 y = _sceneRect.bottom();
128 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
129 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
130 qreal timestampWidth = firstColumnHandle()->sceneLeft();
131 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
132 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
135 for(int i = end; i >= start; i--) {
136 ChatLine *line = new ChatLine(i, model(),
138 timestampWidth, senderWidth, contentsWidth,
139 senderPos, contentsPos);
141 line->setPos(0, y-h);
142 _lines.insert(start, line);
146 for(int i = start; i <= end; i++) {
147 ChatLine *line = new ChatLine(i, model(),
149 timestampWidth, senderWidth, contentsWidth,
150 senderPos, contentsPos);
151 line->setPos(0, y+h);
153 _lines.insert(i, line);
158 // update existing items
159 for(int i = end+1; i < _lines.count(); i++) {
160 _lines[i]->setRow(i);
164 if(_selectionStart >= 0) {
165 int offset = end - start + 1;
166 if(_selectionStart >= start) _selectionStart += offset;
167 if(_selectionEnd >= start) _selectionEnd += offset;
168 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
169 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
172 // neither pre- or append means we have to do dirty work: move items...
173 if(!(atTop || atBottom)) {
176 int moveEnd = _lines.count() - 1;
177 // move top means: moving 0 to end (aka: end + 1)
178 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
179 if(end + 1 < _lines.count() - end - 1) {
189 for(int i = moveStart; i <= moveEnd; i++) {
191 line->setPos(0, line->pos().y() + offset);
195 // check if all went right
196 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
197 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
200 if(start < _firstLineRow) {
201 int prevFirstLineRow = _firstLineRow + (end - start + 1);
202 for(int i = end + 1; i < prevFirstLineRow; i++) {
203 _lines.at(i)->show();
206 // force new search for first proper line
210 if(atBottom || (!atTop && !moveTop)) {
211 emit lastLineChanged(_lines.last(), h);
215 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
218 qreal h = 0; // total height of removed items;
220 bool atTop = (start == 0);
221 bool atBottom = (end == _lines.count() - 1);
222 bool moveTop = false;
224 // remove items from scene
225 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
226 int lineCount = start;
227 while(lineIter != _lines.end() && lineCount <= end) {
228 h += (*lineIter)->height();
230 lineIter = _lines.erase(lineIter);
234 // update rows of remaining chatlines
235 for(int i = start; i < _lines.count(); i++) {
236 _lines.at(i)->setRow(i);
240 if(_selectionStart >= 0) {
241 int offset = end - start + 1;
242 if(_selectionStart >= start)
243 _selectionStart -= offset;
244 if(_selectionEnd >= start)
245 _selectionEnd -= offset;
246 if(_firstSelectionRow >= start)
247 _firstSelectionRow -= offset;
248 if(_lastSelectionRow >= start)
249 _lastSelectionRow -= offset;
252 // neither removing at bottom or top means we have to move items...
253 if(!(atTop || atBottom)) {
256 int moveEnd = _lines.count() - 1;
257 if(start < _lines.count() - start) {
267 for(int i = moveStart; i <= moveEnd; i++) {
269 line->setPos(0, line->pos().y() + offset);
273 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
274 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
277 // when searching for the first non-date-line we have to take into account that our
278 // model still contains the just removed lines so we cannot simply call updateSceneRect()
279 int numRows = model()->rowCount();
280 QModelIndex firstLineIdx;
282 bool needOffset = false;
285 if(_firstLineRow >= start && _firstLineRow <= end) {
286 _firstLineRow = end + 1;
289 firstLineIdx = model()->index(_firstLineRow, 0);
290 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
293 _firstLineRow -= end - start + 1;
297 void ChatScene::updateForViewport(qreal width, qreal height) {
298 _viewportHeight = height;
302 // setWidth is used for 2 things:
303 // a) updating the scene to fit the width of the corresponding view
304 // b) to update the positions of the items if a columhandle has changed it's position
305 // forceReposition is true in the second case
306 // this method features some codeduplication for the sake of performance
307 void ChatScene::setWidth(qreal width, bool forceReposition) {
308 if(width == _sceneRect.width() && !forceReposition)
311 // clock_t startT = clock();
313 qreal linePos = _sceneRect.y() + _sceneRect.height();
314 QList<ChatLine *>::iterator lineIter = _lines.end();
315 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
317 qreal lineHeight = 0;
318 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
320 if(forceReposition) {
321 qreal timestampWidth = firstColumnHandle()->sceneLeft();
322 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
323 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
324 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
325 while(lineIter != lineIterBegin) {
328 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
329 linePos -= lineHeight;
330 line->setPos(0, linePos);
333 while(lineIter != lineIterBegin) {
336 lineHeight = line->setGeometryByWidth(width, contentsWidth);
337 linePos -= lineHeight;
338 line->setPos(0, linePos);
342 updateSceneRect(width);
345 // clock_t endT = clock();
346 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
349 void ChatScene::handlePositionChanged(qreal xpos) {
350 bool first = (sender() == firstColHandle);
353 oldx = firstColHandlePos;
354 firstColHandlePos = xpos;
356 oldx = secondColHandlePos;
357 secondColHandlePos = xpos;
360 ChatViewSettings viewSettings(this);
361 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
362 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
364 ChatViewSettings defaultSettings;
365 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
366 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
368 setWidth(width(), true); // readjust all chatlines
369 // we get ugly redraw errors if we don't update this explicitly... :(
370 // width() should be the same for both handles, so just use firstColHandle regardless
371 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
374 void ChatScene::setHandleXLimits() {
375 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
376 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
379 void ChatScene::setSelectingItem(ChatItem *item) {
380 if(_selectingItem) _selectingItem->clearSelection();
381 _selectingItem = item;
384 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
385 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
386 _selectionStartCol = _selectionMinCol = item->column();
388 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
389 updateSelection(item->mapToScene(itemPos));
392 void ChatScene::updateSelection(const QPointF &pos) {
393 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
394 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
395 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
396 if(!contentItem) return;
398 int curRow = contentItem->row();
400 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
401 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
402 else curColumn = ChatLineModel::TimestampColumn;
404 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
405 if(minColumn != _selectionMinCol) {
406 _selectionMinCol = minColumn;
407 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
408 _lines[l]->setSelected(true, minColumn);
411 int newstart = qMin(curRow, _firstSelectionRow);
412 int newend = qMax(curRow, _firstSelectionRow);
413 if(newstart < _selectionStart) {
414 for(int l = newstart; l < _selectionStart; l++)
415 _lines[l]->setSelected(true, minColumn);
417 if(newstart > _selectionStart) {
418 for(int l = _selectionStart; l < newstart; l++)
419 _lines[l]->setSelected(false);
421 if(newend > _selectionEnd) {
422 for(int l = _selectionEnd+1; l <= newend; l++)
423 _lines[l]->setSelected(true, minColumn);
425 if(newend < _selectionEnd) {
426 for(int l = newend+1; l <= _selectionEnd; l++)
427 _lines[l]->setSelected(false);
430 _selectionStart = newstart;
431 _selectionEnd = newend;
432 _lastSelectionRow = curRow;
434 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
435 if(!_selectingItem) {
436 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
439 _lines[curRow]->setSelected(false);
440 _isSelecting = false;
441 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
445 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
446 if(_isSelecting && event->buttons() == Qt::LeftButton) {
447 updateSelection(event->scenePos());
450 QGraphicsScene::mouseMoveEvent(event);
454 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
455 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
456 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
457 _lines[l]->setSelected(false);
459 _selectionStart = -1;
460 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
462 QGraphicsScene::mousePressEvent(event);
466 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
467 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
468 putToClipboard(selectionToString());
469 _isSelecting = false;
472 QGraphicsScene::mouseReleaseEvent(event);
476 void ChatScene::putToClipboard(const QString &selection) {
477 // TODO Configure clipboards
479 QApplication::clipboard()->setText(selection, QClipboard::Selection);
482 QApplication::clipboard()->setText(selection);
486 //!\brief Convert current selection to human-readable string.
487 QString ChatScene::selectionToString() const {
488 //TODO Make selection format configurable!
489 if(!_isSelecting) return QString();
490 int start = qMin(_selectionStart, _selectionEnd);
491 int end = qMax(_selectionStart, _selectionEnd);
492 if(start < 0 || end >= _lines.count()) {
493 qDebug() << "Invalid selection range:" << start << end;
497 for(int l = start; l <= end; l++) {
498 if(_selectionMinCol == ChatLineModel::TimestampColumn)
499 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
500 if(_selectionMinCol <= ChatLineModel::SenderColumn)
501 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
502 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
507 void ChatScene::requestBacklog() {
508 static const int REQUEST_COUNT = 500;
509 int backlogSize = model()->rowCount();
510 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
511 QModelIndex msgIdx = model()->index(0, 0);
512 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
513 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
515 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
516 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
517 _lastBacklogSize = backlogSize;
518 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
522 int ChatScene::sectionByScenePos(int x) {
523 if(x < firstColHandle->x())
524 return ChatLineModel::TimestampColumn;
525 if(x < secondColHandle->x())
526 return ChatLineModel::SenderColumn;
528 return ChatLineModel::ContentsColumn;
531 void ChatScene::updateSceneRect() {
532 if(_lines.isEmpty()) {
533 updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
537 // we hide day change messages at the top by making the scene rect smaller
538 // and by calling QGraphicsItem::hide() on all leading day change messages
539 // the first one is needed to ensure proper scrollbar ranges
540 // the second for cases where the viewport is larger then the set scenerect
541 // (in this case the items are shown anyways)
542 if(_firstLineRow == -1) {
543 int numRows = model()->rowCount();
545 QModelIndex firstLineIdx;
546 while(_firstLineRow < numRows) {
547 firstLineIdx = model()->index(_firstLineRow, 0);
548 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
550 _lines.at(_firstLineRow)->hide();
555 // the following call should be safe. If it crashes something went wrong during insert/remove
556 ChatLine *firstLine = _lines.at(_firstLineRow);
557 ChatLine *lastLine = _lines.last();
558 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
561 void ChatScene::updateSceneRect(qreal width) {
562 _sceneRect.setWidth(width);
566 void ChatScene::updateSceneRect(const QRectF &rect) {
572 void ChatScene::customEvent(QEvent *event) {
573 switch(event->type()) {
574 case ClearWebPreviewEventType:
575 clearWebPreviewEvent((ClearWebPreviewEvent *)event);
582 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
588 if(webPreview.parentItem != parentItem)
589 webPreview.parentItem = parentItem;
591 if(webPreview.url != url) {
592 webPreview.url = url;
593 // load a new web view and delete the old one (if exists)
594 if(webPreview.previewItem) {
595 removeItem(webPreview.previewItem);
596 delete webPreview.previewItem;
598 webPreview.previewItem = new WebPreviewItem(url);
599 webPreview.delayTimer.start(2000);
601 if(webPreview.urlRect != urlRect) {
602 webPreview.urlRect = urlRect;
603 qreal previewY = urlRect.bottom();
604 qreal previewX = urlRect.x();
605 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
606 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
608 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
609 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
611 webPreview.previewItem->setPos(previewX, previewY);
616 void ChatScene::clearWebPreview(ChatItem *parentItem) {
620 if(parentItem == 0 || webPreview.parentItem == parentItem) {
621 // posting an event ensures that the item will not be removed as
622 // the result of another event. this could result in bad segfaults
623 QCoreApplication::postEvent(this, new ClearWebPreviewEvent());
628 void ChatScene::showWebPreview() {
630 if(webPreview.previewItem)
631 addItem(webPreview.previewItem);
635 void ChatScene::clearWebPreviewEvent(ClearWebPreviewEvent *event) {
638 if(webPreview.previewItem) {
639 if(webPreview.previewItem->scene()) {
640 removeItem(webPreview.previewItem);
642 delete webPreview.previewItem;
643 webPreview.previewItem = 0;
645 webPreview.parentItem = 0;
646 webPreview.url = QString();
647 webPreview.urlRect = QRectF();
651 bool ChatScene::eventFilter(QObject *watched, QEvent *event) {
652 qDebug() << watched << event;