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);
196 if(start < _firstLineRow) {
197 int prevFirstLineRow = _firstLineRow + (end - start + 1);
198 for(int i = end + 1; i < prevFirstLineRow; i++) {
199 _lines.at(i)->show();
202 // force new search for first proper line
206 if(atBottom || (!atTop && !moveTop)) {
207 emit lastLineChanged(_lines.last(), h);
211 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
214 qreal h = 0; // total height of removed items;
216 bool atTop = (start == 0);
217 bool atBottom = (end == _lines.count() - 1);
218 bool moveTop = false;
220 // remove items from scene
221 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
222 int lineCount = start;
223 while(lineIter != _lines.end() && lineCount <= end) {
224 h += (*lineIter)->height();
226 lineIter = _lines.erase(lineIter);
230 // update rows of remaining chatlines
231 for(int i = start; i < _lines.count(); i++) {
232 _lines.at(i)->setRow(i);
236 if(_selectionStart >= 0) {
237 int offset = end - start + 1;
238 if(_selectionStart >= start)
239 _selectionStart -= offset;
240 if(_selectionEnd >= start)
241 _selectionEnd -= offset;
242 if(_firstSelectionRow >= start)
243 _firstSelectionRow -= offset;
244 if(_lastSelectionRow >= start)
245 _lastSelectionRow -= offset;
248 // neither removing at bottom or top means we have to move items...
249 if(!(atTop || atBottom)) {
252 int moveEnd = _lines.count() - 1;
253 if(start < _lines.count() - start) {
263 for(int i = moveStart; i <= moveEnd; i++) {
265 line->setPos(0, line->pos().y() + offset);
271 // when searching for the first non-date-line we have to take into account that our
272 // model still contains the just removed lines so we cannot simply call updateSceneRect()
273 int numRows = model()->rowCount();
274 QModelIndex firstLineIdx;
276 bool needOffset = false;
279 if(_firstLineRow >= start && _firstLineRow <= end) {
280 _firstLineRow = end + 1;
283 firstLineIdx = model()->index(_firstLineRow, 0);
284 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
287 _firstLineRow -= end - start + 1;
291 void ChatScene::updateForViewport(qreal width, qreal height) {
292 _viewportHeight = height;
296 // setWidth is used for 2 things:
297 // a) updating the scene to fit the width of the corresponding view
298 // b) to update the positions of the items if a columhandle has changed it's position
299 // forceReposition is true in the second case
300 // this method features some codeduplication for the sake of performance
301 void ChatScene::setWidth(qreal width, bool forceReposition) {
302 if(width == _sceneRect.width() && !forceReposition)
305 // clock_t startT = clock();
307 qreal linePos = _sceneRect.y() + _sceneRect.height();
308 QList<ChatLine *>::iterator lineIter = _lines.end();
309 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
311 qreal lineHeight = 0;
312 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
314 if(forceReposition) {
315 qreal timestampWidth = firstColumnHandle()->sceneLeft();
316 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
317 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
318 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
319 while(lineIter != lineIterBegin) {
322 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
323 linePos -= lineHeight;
324 line->setPos(0, linePos);
327 while(lineIter != lineIterBegin) {
330 lineHeight = line->setGeometryByWidth(width, contentsWidth);
331 linePos -= lineHeight;
332 line->setPos(0, linePos);
336 updateSceneRect(width);
339 // clock_t endT = clock();
340 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
343 void ChatScene::handlePositionChanged(qreal xpos) {
344 bool first = (sender() == firstColHandle);
347 oldx = firstColHandlePos;
348 firstColHandlePos = xpos;
350 oldx = secondColHandlePos;
351 secondColHandlePos = xpos;
354 ChatViewSettings viewSettings(this);
355 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
356 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
358 ChatViewSettings defaultSettings;
359 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
360 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
362 setWidth(width(), true); // readjust all chatlines
363 // we get ugly redraw errors if we don't update this explicitly... :(
364 // width() should be the same for both handles, so just use firstColHandle regardless
365 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
368 void ChatScene::setHandleXLimits() {
369 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
370 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
373 void ChatScene::setSelectingItem(ChatItem *item) {
374 if(_selectingItem) _selectingItem->clearSelection();
375 _selectingItem = item;
378 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
379 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
380 _selectionStartCol = _selectionMinCol = item->column();
382 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
383 updateSelection(item->mapToScene(itemPos));
386 void ChatScene::updateSelection(const QPointF &pos) {
387 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
388 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
389 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
390 if(!contentItem) return;
392 int curRow = contentItem->row();
394 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
395 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
396 else curColumn = ChatLineModel::TimestampColumn;
398 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
399 if(minColumn != _selectionMinCol) {
400 _selectionMinCol = minColumn;
401 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
402 _lines[l]->setSelected(true, minColumn);
405 int newstart = qMin(curRow, _firstSelectionRow);
406 int newend = qMax(curRow, _firstSelectionRow);
407 if(newstart < _selectionStart) {
408 for(int l = newstart; l < _selectionStart; l++)
409 _lines[l]->setSelected(true, minColumn);
411 if(newstart > _selectionStart) {
412 for(int l = _selectionStart; l < newstart; l++)
413 _lines[l]->setSelected(false);
415 if(newend > _selectionEnd) {
416 for(int l = _selectionEnd+1; l <= newend; l++)
417 _lines[l]->setSelected(true, minColumn);
419 if(newend < _selectionEnd) {
420 for(int l = newend+1; l <= _selectionEnd; l++)
421 _lines[l]->setSelected(false);
424 _selectionStart = newstart;
425 _selectionEnd = newend;
426 _lastSelectionRow = curRow;
428 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
429 if(!_selectingItem) {
430 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
433 _lines[curRow]->setSelected(false);
434 _isSelecting = false;
435 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
439 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
440 if(_isSelecting && event->buttons() == Qt::LeftButton) {
441 updateSelection(event->scenePos());
444 QGraphicsScene::mouseMoveEvent(event);
448 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
449 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
450 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
451 _lines[l]->setSelected(false);
453 _selectionStart = -1;
454 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
456 QGraphicsScene::mousePressEvent(event);
460 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
461 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
462 putToClipboard(selectionToString());
463 _isSelecting = false;
466 QGraphicsScene::mouseReleaseEvent(event);
470 void ChatScene::putToClipboard(const QString &selection) {
471 // TODO Configure clipboards
473 QApplication::clipboard()->setText(selection, QClipboard::Selection);
476 QApplication::clipboard()->setText(selection);
480 //!\brief Convert current selection to human-readable string.
481 QString ChatScene::selectionToString() const {
482 //TODO Make selection format configurable!
483 if(!_isSelecting) return QString();
484 int start = qMin(_selectionStart, _selectionEnd);
485 int end = qMax(_selectionStart, _selectionEnd);
486 if(start < 0 || end >= _lines.count()) {
487 qDebug() << "Invalid selection range:" << start << end;
491 for(int l = start; l <= end; l++) {
492 if(_selectionMinCol == ChatLineModel::TimestampColumn)
493 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
494 if(_selectionMinCol <= ChatLineModel::SenderColumn)
495 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
496 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
501 void ChatScene::requestBacklog() {
502 static const int REQUEST_COUNT = 500;
503 int backlogSize = model()->rowCount();
504 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
505 QModelIndex msgIdx = model()->index(0, 0);
506 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
507 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
509 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
510 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
511 _lastBacklogSize = backlogSize;
512 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
516 int ChatScene::sectionByScenePos(int x) {
517 if(x < firstColHandle->x())
518 return ChatLineModel::TimestampColumn;
519 if(x < secondColHandle->x())
520 return ChatLineModel::SenderColumn;
522 return ChatLineModel::ContentsColumn;
525 void ChatScene::updateSceneRect() {
526 if(_lines.isEmpty()) {
527 updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
531 // we hide day change messages at the top by making the scene rect smaller
532 // and by calling QGraphicsItem::hide() on all leading day change messages
533 // the first one is needed to ensure proper scrollbar ranges
534 // the second for cases where the viewport is larger then the set scenerect
535 // (in this case the items are shown anyways)
536 if(_firstLineRow == -1) {
537 int numRows = model()->rowCount();
539 QModelIndex firstLineIdx;
540 while(_firstLineRow < numRows) {
541 firstLineIdx = model()->index(_firstLineRow, 0);
542 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
544 _lines.at(_firstLineRow)->hide();
549 // the following call should be safe. If it crashes something went wrong during insert/remove
550 ChatLine *firstLine = _lines.at(_firstLineRow);
551 ChatLine *lastLine = _lines.last();
552 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
555 void ChatScene::updateSceneRect(qreal width) {
556 _sceneRect.setWidth(width);
560 void ChatScene::updateSceneRect(const QRectF &rect) {
566 void ChatScene::customEvent(QEvent *event) {
567 switch(event->type()) {
568 case ClearWebPreviewEventType:
569 clearWebPreviewEvent((ClearWebPreviewEvent *)event);
576 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
582 if(webPreview.parentItem != parentItem)
583 webPreview.parentItem = parentItem;
585 if(webPreview.url != url) {
586 webPreview.url = url;
587 // load a new web view and delete the old one (if exists)
588 if(webPreview.previewItem) {
589 removeItem(webPreview.previewItem);
590 delete webPreview.previewItem;
592 webPreview.previewItem = new WebPreviewItem(url);
593 webPreview.delayTimer.start(2000);
595 if(webPreview.urlRect != urlRect) {
596 webPreview.urlRect = urlRect;
597 qreal previewY = urlRect.bottom();
598 qreal previewX = urlRect.x();
599 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
600 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
602 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
603 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
605 webPreview.previewItem->setPos(previewX, previewY);
610 void ChatScene::clearWebPreview(ChatItem *parentItem) {
614 if(parentItem == 0 || webPreview.parentItem == parentItem) {
615 // posting an event ensures that the item will not be removed as
616 // the result of another event. this could result in bad segfaults
617 QCoreApplication::postEvent(this, new ClearWebPreviewEvent());
622 void ChatScene::showWebPreview() {
624 if(webPreview.previewItem)
625 addItem(webPreview.previewItem);
629 void ChatScene::clearWebPreviewEvent(ClearWebPreviewEvent *event) {
632 if(webPreview.previewItem) {
633 if(webPreview.previewItem->scene()) {
634 removeItem(webPreview.previewItem);
636 delete webPreview.previewItem;
637 webPreview.previewItem = 0;
639 webPreview.parentItem = 0;
640 webPreview.url = QString();
641 webPreview.urlRect = QRectF();
645 bool ChatScene::eventFilter(QObject *watched, QEvent *event) {
646 qDebug() << watched << event;