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);
275 // when searching for the first non-date-line we have to take into account that our
276 // model still contains the just removed lines so we cannot simply call updateSceneRect()
277 int numRows = model()->rowCount();
278 QModelIndex firstLineIdx;
280 bool needOffset = false;
283 if(_firstLineRow >= start && _firstLineRow <= end) {
284 _firstLineRow = end + 1;
287 firstLineIdx = model()->index(_firstLineRow, 0);
288 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
291 _firstLineRow -= end - start + 1;
295 void ChatScene::updateForViewport(qreal width, qreal height) {
296 _viewportHeight = height;
300 // setWidth is used for 2 things:
301 // a) updating the scene to fit the width of the corresponding view
302 // b) to update the positions of the items if a columhandle has changed it's position
303 // forceReposition is true in the second case
304 // this method features some codeduplication for the sake of performance
305 void ChatScene::setWidth(qreal width, bool forceReposition) {
306 if(width == _sceneRect.width() && !forceReposition)
309 // clock_t startT = clock();
311 qreal linePos = _sceneRect.y() + _sceneRect.height();
312 QList<ChatLine *>::iterator lineIter = _lines.end();
313 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
315 qreal lineHeight = 0;
316 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
318 if(forceReposition) {
319 qreal timestampWidth = firstColumnHandle()->sceneLeft();
320 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
321 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
322 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
323 while(lineIter != lineIterBegin) {
326 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
327 linePos -= lineHeight;
328 line->setPos(0, linePos);
331 while(lineIter != lineIterBegin) {
334 lineHeight = line->setGeometryByWidth(width, contentsWidth);
335 linePos -= lineHeight;
336 line->setPos(0, linePos);
340 updateSceneRect(width);
343 // clock_t endT = clock();
344 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
347 void ChatScene::handlePositionChanged(qreal xpos) {
348 bool first = (sender() == firstColHandle);
351 oldx = firstColHandlePos;
352 firstColHandlePos = xpos;
354 oldx = secondColHandlePos;
355 secondColHandlePos = xpos;
358 ChatViewSettings viewSettings(this);
359 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
360 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
362 ChatViewSettings defaultSettings;
363 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
364 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
366 setWidth(width(), true); // readjust all chatlines
367 // we get ugly redraw errors if we don't update this explicitly... :(
368 // width() should be the same for both handles, so just use firstColHandle regardless
369 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
372 void ChatScene::setHandleXLimits() {
373 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
374 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
377 void ChatScene::setSelectingItem(ChatItem *item) {
378 if(_selectingItem) _selectingItem->clearSelection();
379 _selectingItem = item;
382 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
383 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
384 _selectionStartCol = _selectionMinCol = item->column();
386 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
387 updateSelection(item->mapToScene(itemPos));
390 void ChatScene::updateSelection(const QPointF &pos) {
391 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
392 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
393 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
394 if(!contentItem) return;
396 int curRow = contentItem->row();
398 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
399 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
400 else curColumn = ChatLineModel::TimestampColumn;
402 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
403 if(minColumn != _selectionMinCol) {
404 _selectionMinCol = minColumn;
405 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
406 _lines[l]->setSelected(true, minColumn);
409 int newstart = qMin(curRow, _firstSelectionRow);
410 int newend = qMax(curRow, _firstSelectionRow);
411 if(newstart < _selectionStart) {
412 for(int l = newstart; l < _selectionStart; l++)
413 _lines[l]->setSelected(true, minColumn);
415 if(newstart > _selectionStart) {
416 for(int l = _selectionStart; l < newstart; l++)
417 _lines[l]->setSelected(false);
419 if(newend > _selectionEnd) {
420 for(int l = _selectionEnd+1; l <= newend; l++)
421 _lines[l]->setSelected(true, minColumn);
423 if(newend < _selectionEnd) {
424 for(int l = newend+1; l <= _selectionEnd; l++)
425 _lines[l]->setSelected(false);
428 _selectionStart = newstart;
429 _selectionEnd = newend;
430 _lastSelectionRow = curRow;
432 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
433 if(!_selectingItem) {
434 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
437 _lines[curRow]->setSelected(false);
438 _isSelecting = false;
439 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
443 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
444 if(_isSelecting && event->buttons() == Qt::LeftButton) {
445 updateSelection(event->scenePos());
448 QGraphicsScene::mouseMoveEvent(event);
452 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
453 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
454 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
455 _lines[l]->setSelected(false);
457 _selectionStart = -1;
458 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
460 QGraphicsScene::mousePressEvent(event);
464 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
465 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
466 putToClipboard(selectionToString());
467 _isSelecting = false;
470 QGraphicsScene::mouseReleaseEvent(event);
474 void ChatScene::putToClipboard(const QString &selection) {
475 // TODO Configure clipboards
477 QApplication::clipboard()->setText(selection, QClipboard::Selection);
480 QApplication::clipboard()->setText(selection);
484 //!\brief Convert current selection to human-readable string.
485 QString ChatScene::selectionToString() const {
486 //TODO Make selection format configurable!
487 if(!_isSelecting) return QString();
488 int start = qMin(_selectionStart, _selectionEnd);
489 int end = qMax(_selectionStart, _selectionEnd);
490 if(start < 0 || end >= _lines.count()) {
491 qDebug() << "Invalid selection range:" << start << end;
495 for(int l = start; l <= end; l++) {
496 if(_selectionMinCol == ChatLineModel::TimestampColumn)
497 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
498 if(_selectionMinCol <= ChatLineModel::SenderColumn)
499 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
500 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
505 void ChatScene::requestBacklog() {
506 static const int REQUEST_COUNT = 500;
507 int backlogSize = model()->rowCount();
508 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
509 QModelIndex msgIdx = model()->index(0, 0);
510 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
511 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
513 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
514 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
515 _lastBacklogSize = backlogSize;
516 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
520 int ChatScene::sectionByScenePos(int x) {
521 if(x < firstColHandle->x())
522 return ChatLineModel::TimestampColumn;
523 if(x < secondColHandle->x())
524 return ChatLineModel::SenderColumn;
526 return ChatLineModel::ContentsColumn;
529 void ChatScene::updateSceneRect() {
530 if(_lines.isEmpty()) {
531 updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
535 // we hide day change messages at the top by making the scene rect smaller
536 // and by calling QGraphicsItem::hide() on all leading day change messages
537 // the first one is needed to ensure proper scrollbar ranges
538 // the second for cases where the viewport is larger then the set scenerect
539 // (in this case the items are shown anyways)
540 if(_firstLineRow == -1) {
541 int numRows = model()->rowCount();
543 QModelIndex firstLineIdx;
544 while(_firstLineRow < numRows) {
545 firstLineIdx = model()->index(_firstLineRow, 0);
546 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
548 _lines.at(_firstLineRow)->hide();
553 // the following call should be safe. If it crashes something went wrong during insert/remove
554 ChatLine *firstLine = _lines.at(_firstLineRow);
555 ChatLine *lastLine = _lines.last();
556 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
559 void ChatScene::updateSceneRect(qreal width) {
560 _sceneRect.setWidth(width);
564 void ChatScene::updateSceneRect(const QRectF &rect) {
570 void ChatScene::customEvent(QEvent *event) {
571 switch(event->type()) {
572 case ClearWebPreviewEventType:
573 clearWebPreviewEvent((ClearWebPreviewEvent *)event);
580 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
586 if(webPreview.parentItem != parentItem)
587 webPreview.parentItem = parentItem;
589 if(webPreview.url != url) {
590 webPreview.url = url;
591 // load a new web view and delete the old one (if exists)
592 if(webPreview.previewItem) {
593 removeItem(webPreview.previewItem);
594 delete webPreview.previewItem;
596 webPreview.previewItem = new WebPreviewItem(url);
597 webPreview.delayTimer.start(2000);
599 if(webPreview.urlRect != urlRect) {
600 webPreview.urlRect = urlRect;
601 qreal previewY = urlRect.bottom();
602 qreal previewX = urlRect.x();
603 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
604 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
606 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
607 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
609 webPreview.previewItem->setPos(previewX, previewY);
614 void ChatScene::clearWebPreview(ChatItem *parentItem) {
618 if(parentItem == 0 || webPreview.parentItem == parentItem) {
619 // posting an event ensures that the item will not be removed as
620 // the result of another event. this could result in bad segfaults
621 QCoreApplication::postEvent(this, new ClearWebPreviewEvent());
626 void ChatScene::showWebPreview() {
628 if(webPreview.previewItem)
629 addItem(webPreview.previewItem);
633 void ChatScene::clearWebPreviewEvent(ClearWebPreviewEvent *event) {
636 if(webPreview.previewItem) {
637 if(webPreview.previewItem->scene()) {
638 removeItem(webPreview.previewItem);
640 delete webPreview.previewItem;
641 webPreview.previewItem = 0;
643 webPreview.parentItem = 0;
644 webPreview.url = QString();
645 webPreview.urlRect = QRectF();
649 bool ChatScene::eventFilter(QObject *watched, QEvent *event) {
650 qDebug() << watched << event;