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()));
97 webPreview.deleteTimer.setInterval(600000);
98 connect(&webPreview.deleteTimer, SIGNAL(timeout()), this, SLOT(deleteWebPreview()));
101 ChatScene::~ChatScene() {
104 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
106 // QModelIndex sidx = model()->index(start, 0);
107 // QModelIndex eidx = model()->index(end, 0);
108 // qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
111 qreal y = _sceneRect.y();
112 qreal width = _sceneRect.width();
114 bool atBottom = false;
115 bool moveTop = false;
117 if(start > 0 && start < _lines.count()) {
118 y = _lines.value(start)->y();
121 if(start == _lines.count()) {
122 y = _sceneRect.bottom();
127 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
128 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
129 qreal timestampWidth = firstColumnHandle()->sceneLeft();
130 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
131 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
134 for(int i = end; i >= start; i--) {
135 ChatLine *line = new ChatLine(i, model(),
137 timestampWidth, senderWidth, contentsWidth,
138 senderPos, contentsPos);
140 line->setPos(0, y-h);
141 _lines.insert(start, line);
145 for(int i = start; i <= end; i++) {
146 ChatLine *line = new ChatLine(i, model(),
148 timestampWidth, senderWidth, contentsWidth,
149 senderPos, contentsPos);
150 line->setPos(0, y+h);
152 _lines.insert(i, line);
157 // update existing items
158 for(int i = end+1; i < _lines.count(); i++) {
159 _lines[i]->setRow(i);
163 if(_selectionStart >= 0) {
164 int offset = end - start + 1;
165 if(_selectionStart >= start) _selectionStart += offset;
166 if(_selectionEnd >= start) _selectionEnd += offset;
167 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
168 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
171 // neither pre- or append means we have to do dirty work: move items...
172 if(!(atTop || atBottom)) {
175 int moveEnd = _lines.count() - 1;
176 // move top means: moving 0 to end (aka: end + 1)
177 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
178 if(end + 1 < _lines.count() - end - 1) {
188 for(int i = moveStart; i <= moveEnd; i++) {
190 line->setPos(0, line->pos().y() + offset);
194 // check if all went right
195 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
196 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
199 if(start < _firstLineRow) {
200 int prevFirstLineRow = _firstLineRow + (end - start + 1);
201 for(int i = end + 1; i < prevFirstLineRow; i++) {
202 _lines.at(i)->show();
205 // force new search for first proper line
209 if(atBottom || (!atTop && !moveTop)) {
210 emit lastLineChanged(_lines.last(), h);
214 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
217 qreal h = 0; // total height of removed items;
219 bool atTop = (start == 0);
220 bool atBottom = (end == _lines.count() - 1);
221 bool moveTop = false;
223 // remove items from scene
224 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
225 int lineCount = start;
226 while(lineIter != _lines.end() && lineCount <= end) {
227 h += (*lineIter)->height();
229 lineIter = _lines.erase(lineIter);
233 // update rows of remaining chatlines
234 for(int i = start; i < _lines.count(); i++) {
235 _lines.at(i)->setRow(i);
239 if(_selectionStart >= 0) {
240 int offset = end - start + 1;
241 if(_selectionStart >= start)
242 _selectionStart -= offset;
243 if(_selectionEnd >= start)
244 _selectionEnd -= offset;
245 if(_firstSelectionRow >= start)
246 _firstSelectionRow -= offset;
247 if(_lastSelectionRow >= start)
248 _lastSelectionRow -= offset;
251 // neither removing at bottom or top means we have to move items...
252 if(!(atTop || atBottom)) {
255 int moveEnd = _lines.count() - 1;
256 if(start < _lines.count() - start) {
266 for(int i = moveStart; i <= moveEnd; i++) {
268 line->setPos(0, line->pos().y() + offset);
272 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
273 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
276 // when searching for the first non-date-line we have to take into account that our
277 // model still contains the just removed lines so we cannot simply call updateSceneRect()
278 int numRows = model()->rowCount();
279 QModelIndex firstLineIdx;
281 bool needOffset = false;
284 if(_firstLineRow >= start && _firstLineRow <= end) {
285 _firstLineRow = end + 1;
288 firstLineIdx = model()->index(_firstLineRow, 0);
289 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
292 _firstLineRow -= end - start + 1;
296 void ChatScene::updateForViewport(qreal width, qreal height) {
297 _viewportHeight = height;
301 // setWidth is used for 2 things:
302 // a) updating the scene to fit the width of the corresponding view
303 // b) to update the positions of the items if a columhandle has changed it's position
304 // forceReposition is true in the second case
305 // this method features some codeduplication for the sake of performance
306 void ChatScene::setWidth(qreal width, bool forceReposition) {
307 if(width == _sceneRect.width() && !forceReposition)
310 // clock_t startT = clock();
312 qreal linePos = _sceneRect.y() + _sceneRect.height();
313 QList<ChatLine *>::iterator lineIter = _lines.end();
314 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
316 qreal lineHeight = 0;
317 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
319 if(forceReposition) {
320 qreal timestampWidth = firstColumnHandle()->sceneLeft();
321 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
322 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
323 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
324 while(lineIter != lineIterBegin) {
327 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
328 linePos -= lineHeight;
329 line->setPos(0, linePos);
332 while(lineIter != lineIterBegin) {
335 lineHeight = line->setGeometryByWidth(width, contentsWidth);
336 linePos -= lineHeight;
337 line->setPos(0, linePos);
341 updateSceneRect(width);
344 // clock_t endT = clock();
345 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
348 void ChatScene::handlePositionChanged(qreal xpos) {
349 bool first = (sender() == firstColHandle);
352 oldx = firstColHandlePos;
353 firstColHandlePos = xpos;
355 oldx = secondColHandlePos;
356 secondColHandlePos = xpos;
359 ChatViewSettings viewSettings(this);
360 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
361 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
363 ChatViewSettings defaultSettings;
364 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
365 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
367 setWidth(width(), true); // readjust all chatlines
368 // we get ugly redraw errors if we don't update this explicitly... :(
369 // width() should be the same for both handles, so just use firstColHandle regardless
370 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
373 void ChatScene::setHandleXLimits() {
374 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
375 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
378 void ChatScene::setSelectingItem(ChatItem *item) {
379 if(_selectingItem) _selectingItem->clearSelection();
380 _selectingItem = item;
383 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
384 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
385 _selectionStartCol = _selectionMinCol = item->column();
387 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
388 updateSelection(item->mapToScene(itemPos));
391 void ChatScene::updateSelection(const QPointF &pos) {
392 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
393 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
394 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
395 if(!contentItem) return;
397 int curRow = contentItem->row();
399 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
400 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
401 else curColumn = ChatLineModel::TimestampColumn;
403 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
404 if(minColumn != _selectionMinCol) {
405 _selectionMinCol = minColumn;
406 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
407 _lines[l]->setSelected(true, minColumn);
410 int newstart = qMin(curRow, _firstSelectionRow);
411 int newend = qMax(curRow, _firstSelectionRow);
412 if(newstart < _selectionStart) {
413 for(int l = newstart; l < _selectionStart; l++)
414 _lines[l]->setSelected(true, minColumn);
416 if(newstart > _selectionStart) {
417 for(int l = _selectionStart; l < newstart; l++)
418 _lines[l]->setSelected(false);
420 if(newend > _selectionEnd) {
421 for(int l = _selectionEnd+1; l <= newend; l++)
422 _lines[l]->setSelected(true, minColumn);
424 if(newend < _selectionEnd) {
425 for(int l = newend+1; l <= _selectionEnd; l++)
426 _lines[l]->setSelected(false);
429 _selectionStart = newstart;
430 _selectionEnd = newend;
431 _lastSelectionRow = curRow;
433 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
434 if(!_selectingItem) {
435 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
438 _lines[curRow]->setSelected(false);
439 _isSelecting = false;
440 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
444 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
445 if(_isSelecting && event->buttons() == Qt::LeftButton) {
446 updateSelection(event->scenePos());
449 QGraphicsScene::mouseMoveEvent(event);
453 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
454 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
455 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
456 _lines[l]->setSelected(false);
458 _selectionStart = -1;
459 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
461 QGraphicsScene::mousePressEvent(event);
465 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
466 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
467 putToClipboard(selectionToString());
468 _isSelecting = false;
471 QGraphicsScene::mouseReleaseEvent(event);
475 void ChatScene::putToClipboard(const QString &selection) {
476 // TODO Configure clipboards
478 QApplication::clipboard()->setText(selection, QClipboard::Selection);
481 QApplication::clipboard()->setText(selection);
485 //!\brief Convert current selection to human-readable string.
486 QString ChatScene::selectionToString() const {
487 //TODO Make selection format configurable!
488 if(!_isSelecting) return QString();
489 int start = qMin(_selectionStart, _selectionEnd);
490 int end = qMax(_selectionStart, _selectionEnd);
491 if(start < 0 || end >= _lines.count()) {
492 qDebug() << "Invalid selection range:" << start << end;
496 for(int l = start; l <= end; l++) {
497 if(_selectionMinCol == ChatLineModel::TimestampColumn)
498 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
499 if(_selectionMinCol <= ChatLineModel::SenderColumn)
500 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
501 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
506 void ChatScene::requestBacklog() {
507 static const int REQUEST_COUNT = 500;
508 int backlogSize = model()->rowCount();
509 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
510 QModelIndex msgIdx = model()->index(0, 0);
511 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
512 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
514 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
515 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
516 _lastBacklogSize = backlogSize;
517 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
521 int ChatScene::sectionByScenePos(int x) {
522 if(x < firstColHandle->x())
523 return ChatLineModel::TimestampColumn;
524 if(x < secondColHandle->x())
525 return ChatLineModel::SenderColumn;
527 return ChatLineModel::ContentsColumn;
530 void ChatScene::updateSceneRect() {
531 if(_lines.isEmpty()) {
532 updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
536 // we hide day change messages at the top by making the scene rect smaller
537 // and by calling QGraphicsItem::hide() on all leading day change messages
538 // the first one is needed to ensure proper scrollbar ranges
539 // the second for cases where the viewport is larger then the set scenerect
540 // (in this case the items are shown anyways)
541 if(_firstLineRow == -1) {
542 int numRows = model()->rowCount();
544 QModelIndex firstLineIdx;
545 while(_firstLineRow < numRows) {
546 firstLineIdx = model()->index(_firstLineRow, 0);
547 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
549 _lines.at(_firstLineRow)->hide();
554 // the following call should be safe. If it crashes something went wrong during insert/remove
555 ChatLine *firstLine = _lines.at(_firstLineRow);
556 ChatLine *lastLine = _lines.last();
557 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
560 void ChatScene::updateSceneRect(qreal width) {
561 _sceneRect.setWidth(width);
565 void ChatScene::updateSceneRect(const QRectF &rect) {
571 void ChatScene::customEvent(QEvent *event) {
572 switch(event->type()) {
573 case ClearWebPreviewEventType:
574 clearWebPreviewEvent((ClearWebPreviewEvent *)event);
581 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
587 if(webPreview.parentItem != parentItem)
588 webPreview.parentItem = parentItem;
590 if(webPreview.url != url) {
591 webPreview.url = url;
592 // load a new web view and delete the old one (if exists)
593 if(webPreview.previewItem && webPreview.previewItem->scene()) {
594 removeItem(webPreview.previewItem);
595 delete webPreview.previewItem;
597 webPreview.previewItem = new WebPreviewItem(url);
598 webPreview.delayTimer.start(2000);
599 webPreview.deleteTimer.stop();
600 } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
601 // we just have to readd the item to the scene
602 webPreview.delayTimer.start(2000);
603 webPreview.deleteTimer.stop();
605 if(webPreview.urlRect != urlRect) {
606 webPreview.urlRect = urlRect;
607 qreal previewY = urlRect.bottom();
608 qreal previewX = urlRect.x();
609 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
610 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
612 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
613 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
615 webPreview.previewItem->setPos(previewX, previewY);
620 void ChatScene::clearWebPreview(ChatItem *parentItem) {
624 if(parentItem == 0 || webPreview.parentItem == parentItem) {
625 // posting an event ensures that the item will not be removed as
626 // the result of another event. this could result in bad segfaults
627 QCoreApplication::postEvent(this, new ClearWebPreviewEvent());
632 void ChatScene::showWebPreview() {
634 if(webPreview.previewItem)
635 addItem(webPreview.previewItem);
639 void ChatScene::clearWebPreviewEvent(ClearWebPreviewEvent *event) {
642 if(webPreview.previewItem && webPreview.previewItem->scene()) {
643 removeItem(webPreview.previewItem);
644 webPreview.deleteTimer.start();
646 webPreview.delayTimer.stop();
650 void ChatScene::deleteWebPreview() {
651 if(webPreview.previewItem) {
652 delete webPreview.previewItem;
653 webPreview.previewItem = 0;
655 webPreview.parentItem = 0;
656 webPreview.url = QString();
657 webPreview.urlRect = QRectF();