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 class ClearWebPreviewEvent : public QEvent {
43 inline ClearWebPreviewEvent() : QEvent(QEvent::User) {}
46 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
47 : QGraphicsScene(0, 0, width, 0, parent),
50 _singleBufferScene(false),
51 _sceneRect(0, 0, width, 0),
59 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
61 _singleBufferScene = filter->isSingleBufferFilter();
64 ChatViewSettings defaultSettings;
65 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
66 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
68 ChatViewSettings viewSettings(this);
69 firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
70 secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
72 firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
73 addItem(firstColHandle);
74 firstColHandle->setXPos(firstColHandlePos);
75 connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
76 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
78 secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
79 addItem(secondColHandle);
80 secondColHandle->setXPos(secondColHandlePos);
81 connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
82 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
86 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
87 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
88 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
89 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
91 if(model->rowCount() > 0)
92 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
94 webPreview.delayTimer.setSingleShot(true);
95 connect(&webPreview.delayTimer, SIGNAL(timeout()), this, SLOT(showWebPreview()));
98 ChatScene::~ChatScene() {
101 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
103 // QModelIndex sidx = model()->index(start, 0);
104 // QModelIndex eidx = model()->index(end, 0);
105 // qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
108 qreal y = _sceneRect.y();
109 qreal width = _sceneRect.width();
111 bool atBottom = false;
112 bool moveTop = false;
114 if(start > 0 && start < _lines.count()) {
115 y = _lines.value(start)->y();
118 if(start == _lines.count()) {
119 y = _sceneRect.bottom();
124 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
125 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
126 qreal timestampWidth = firstColumnHandle()->sceneLeft();
127 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
128 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
131 for(int i = end; i >= start; i--) {
132 ChatLine *line = new ChatLine(i, model(),
134 timestampWidth, senderWidth, contentsWidth,
135 senderPos, contentsPos);
137 line->setPos(0, y-h);
138 _lines.insert(start, line);
142 for(int i = start; i <= end; i++) {
143 ChatLine *line = new ChatLine(i, model(),
145 timestampWidth, senderWidth, contentsWidth,
146 senderPos, contentsPos);
147 line->setPos(0, y+h);
149 _lines.insert(i, line);
154 // update existing items
155 for(int i = end+1; i < _lines.count(); i++) {
156 _lines[i]->setRow(i);
160 if(_selectionStart >= 0) {
161 int offset = end - start + 1;
162 if(_selectionStart >= start) _selectionStart += offset;
163 if(_selectionEnd >= start) _selectionEnd += offset;
164 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
165 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
168 // neither pre- or append means we have to do dirty work: move items...
169 if(!(atTop || atBottom)) {
172 int moveEnd = _lines.count() - 1;
173 // move top means: moving 0 to end (aka: end + 1)
174 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
175 if(end + 1 < _lines.count() - end - 1) {
185 for(int i = moveStart; i <= moveEnd; i++) {
187 line->setPos(0, line->pos().y() + offset);
192 if(start < _firstLineRow) {
193 int prevFirstLineRow = _firstLineRow + (end - start + 1);
194 for(int i = end + 1; i < prevFirstLineRow; i++) {
195 _lines.at(i)->show();
198 // force new search for first proper line
203 emit lastLineChanged(_lines.last());
208 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
211 qreal h = 0; // total height of removed items;
213 bool atTop = (start == 0);
214 bool atBottom = (end == _lines.count() - 1);
215 bool moveTop = false;
217 // remove items from scene
218 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
219 int lineCount = start;
220 while(lineIter != _lines.end() && lineCount <= end) {
221 h += (*lineIter)->height();
223 lineIter = _lines.erase(lineIter);
227 // update rows of remaining chatlines
228 for(int i = start; i < _lines.count(); i++) {
229 _lines.at(i)->setRow(i);
233 if(_selectionStart >= 0) {
234 int offset = end - start + 1;
235 if(_selectionStart >= start)
236 _selectionStart -= offset;
237 if(_selectionEnd >= start)
238 _selectionEnd -= offset;
239 if(_firstSelectionRow >= start)
240 _firstSelectionRow -= offset;
241 if(_lastSelectionRow >= start)
242 _lastSelectionRow -= offset;
245 // neither removing at bottom or top means we have to move items...
246 if(!(atTop || atBottom)) {
249 int moveEnd = _lines.count() - 1;
250 if(start < _lines.count() - start) {
260 for(int i = moveStart; i <= moveEnd; i++) {
262 line->setPos(0, line->pos().y() + offset);
268 // when searching for the first non-date-line we have to take into account that our
269 // model still contains the just removed lines so we cannot simply call updateSceneRect()
270 int numRows = model()->rowCount();
271 QModelIndex firstLineIdx;
273 bool needOffset = false;
276 if(_firstLineRow >= start && _firstLineRow <= end) {
277 _firstLineRow = end + 1;
280 firstLineIdx = model()->index(_firstLineRow, 0);
281 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
284 _firstLineRow -= end - start + 1;
288 void ChatScene::updateForViewport(qreal width, qreal height) {
289 _viewportHeight = height;
293 // setWidth is used for 2 things:
294 // a) updating the scene to fit the width of the corresponding view
295 // b) to update the positions of the items if a columhandle has changed it's position
296 // forceReposition is true in the second case
297 // this method features some codeduplication for the sake of performance
298 void ChatScene::setWidth(qreal width, bool forceReposition) {
299 if(width == _sceneRect.width() && !forceReposition)
302 // clock_t startT = clock();
304 qreal linePos = _sceneRect.y() + _sceneRect.height();
305 QList<ChatLine *>::iterator lineIter = _lines.end();
306 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
308 qreal lineHeight = 0;
309 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
311 if(forceReposition) {
312 qreal timestampWidth = firstColumnHandle()->sceneLeft();
313 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
314 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
315 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
316 while(lineIter != lineIterBegin) {
319 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
320 linePos -= lineHeight;
321 line->setPos(0, linePos);
324 while(lineIter != lineIterBegin) {
327 lineHeight = line->setGeometryByWidth(width, contentsWidth);
328 linePos -= lineHeight;
329 line->setPos(0, linePos);
333 updateSceneRect(width);
336 // clock_t endT = clock();
337 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
340 void ChatScene::handlePositionChanged(qreal xpos) {
341 bool first = (sender() == firstColHandle);
344 oldx = firstColHandlePos;
345 firstColHandlePos = xpos;
347 oldx = secondColHandlePos;
348 secondColHandlePos = xpos;
351 ChatViewSettings viewSettings(this);
352 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
353 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
355 ChatViewSettings defaultSettings;
356 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
357 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
359 setWidth(width(), true); // readjust all chatlines
360 // we get ugly redraw errors if we don't update this explicitly... :(
361 // width() should be the same for both handles, so just use firstColHandle regardless
362 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
365 void ChatScene::setHandleXLimits() {
366 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
367 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
370 void ChatScene::setSelectingItem(ChatItem *item) {
371 if(_selectingItem) _selectingItem->clearSelection();
372 _selectingItem = item;
375 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
376 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
377 _selectionStartCol = _selectionMinCol = item->column();
379 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
380 updateSelection(item->mapToScene(itemPos));
383 void ChatScene::updateSelection(const QPointF &pos) {
384 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
385 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
386 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
387 if(!contentItem) return;
389 int curRow = contentItem->row();
391 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
392 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
393 else curColumn = ChatLineModel::TimestampColumn;
395 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
396 if(minColumn != _selectionMinCol) {
397 _selectionMinCol = minColumn;
398 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
399 _lines[l]->setSelected(true, minColumn);
402 int newstart = qMin(curRow, _firstSelectionRow);
403 int newend = qMax(curRow, _firstSelectionRow);
404 if(newstart < _selectionStart) {
405 for(int l = newstart; l < _selectionStart; l++)
406 _lines[l]->setSelected(true, minColumn);
408 if(newstart > _selectionStart) {
409 for(int l = _selectionStart; l < newstart; l++)
410 _lines[l]->setSelected(false);
412 if(newend > _selectionEnd) {
413 for(int l = _selectionEnd+1; l <= newend; l++)
414 _lines[l]->setSelected(true, minColumn);
416 if(newend < _selectionEnd) {
417 for(int l = newend+1; l <= _selectionEnd; l++)
418 _lines[l]->setSelected(false);
421 _selectionStart = newstart;
422 _selectionEnd = newend;
423 _lastSelectionRow = curRow;
425 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
426 if(!_selectingItem) {
427 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
430 _lines[curRow]->setSelected(false);
431 _isSelecting = false;
432 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
436 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
437 if(_isSelecting && event->buttons() == Qt::LeftButton) {
438 updateSelection(event->scenePos());
441 QGraphicsScene::mouseMoveEvent(event);
445 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
446 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
447 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
448 _lines[l]->setSelected(false);
450 _selectionStart = -1;
451 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
453 QGraphicsScene::mousePressEvent(event);
457 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
458 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
459 putToClipboard(selectionToString());
460 _isSelecting = false;
463 QGraphicsScene::mouseReleaseEvent(event);
467 void ChatScene::putToClipboard(const QString &selection) {
468 // TODO Configure clipboards
470 QApplication::clipboard()->setText(selection, QClipboard::Selection);
473 QApplication::clipboard()->setText(selection);
477 //!\brief Convert current selection to human-readable string.
478 QString ChatScene::selectionToString() const {
479 //TODO Make selection format configurable!
480 if(!_isSelecting) return QString();
481 int start = qMin(_selectionStart, _selectionEnd);
482 int end = qMax(_selectionStart, _selectionEnd);
483 if(start < 0 || end >= _lines.count()) {
484 qDebug() << "Invalid selection range:" << start << end;
488 for(int l = start; l <= end; l++) {
489 if(_selectionMinCol == ChatLineModel::TimestampColumn)
490 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
491 if(_selectionMinCol <= ChatLineModel::SenderColumn)
492 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
493 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
498 void ChatScene::requestBacklog() {
499 static const int REQUEST_COUNT = 500;
500 int backlogSize = model()->rowCount();
501 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
502 QModelIndex msgIdx = model()->index(0, 0);
503 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
504 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
506 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
507 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
508 _lastBacklogSize = backlogSize;
509 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
513 int ChatScene::sectionByScenePos(int x) {
514 if(x < firstColHandle->x())
515 return ChatLineModel::TimestampColumn;
516 if(x < secondColHandle->x())
517 return ChatLineModel::SenderColumn;
519 return ChatLineModel::ContentsColumn;
522 void ChatScene::updateSceneRect() {
523 if(_lines.isEmpty()) {
524 updateSceneRect(QRectF(0, 0, _sceneRect.width(), 0));
528 // we hide day change messages at the top by making the scene rect smaller
529 // and by calling QGraphicsItem::hide() on all leading day change messages
530 // the first one is needed to ensure proper scrollbar ranges
531 // the second for cases where the viewport is larger then the set scenerect
532 // (in this case the items are shown anyways)
533 if(_firstLineRow == -1) {
534 int numRows = model()->rowCount();
536 QModelIndex firstLineIdx;
537 while(_firstLineRow < numRows) {
538 firstLineIdx = model()->index(_firstLineRow, 0);
539 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
541 _lines.at(_firstLineRow)->hide();
546 // the following call should be safe. If it crashes something went wrong during insert/remove
547 ChatLine *firstLine = _lines.at(_firstLineRow);
548 ChatLine *lastLine = _lines.last();
549 updateSceneRect(QRectF(0, firstLine->pos().y(), _sceneRect.width(), lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
552 void ChatScene::updateSceneRect(qreal width) {
553 _sceneRect.setWidth(width);
557 void ChatScene::updateSceneRect(const QRectF &rect) {
562 void ChatScene::customEvent(QEvent *event) {
563 if(event->type() != QEvent::User)
567 clearWebPreviewEvent();
570 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
576 if(webPreview.parentItem != parentItem)
577 webPreview.parentItem = parentItem;
579 if(webPreview.url != url) {
580 webPreview.url = url;
581 // load a new web view and delete the old one (if exists)
582 if(webPreview.previewItem) {
583 removeItem(webPreview.previewItem);
584 delete webPreview.previewItem;
586 webPreview.previewItem = new WebPreviewItem(url);
587 webPreview.delayTimer.start(2000);
589 if(webPreview.urlRect != urlRect) {
590 webPreview.urlRect = urlRect;
591 qreal previewY = urlRect.bottom();
592 qreal previewX = urlRect.x();
593 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
594 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
596 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
597 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
599 webPreview.previewItem->setPos(previewX, previewY);
604 void ChatScene::clearWebPreview(ChatItem *parentItem) {
608 if(parentItem == 0 || webPreview.parentItem == parentItem) {
609 // posting an event ensures that the item will not be removed as
610 // the result of another event. this could result in bad segfaults
611 QCoreApplication::postEvent(this, new ClearWebPreviewEvent());
616 void ChatScene::showWebPreview() {
618 if(webPreview.previewItem)
619 addItem(webPreview.previewItem);
623 void ChatScene::clearWebPreviewEvent() {
625 if(webPreview.previewItem) {
626 if(!webPreview.delayTimer.isActive())
627 removeItem(webPreview.previewItem);
629 webPreview.delayTimer.stop();
630 delete webPreview.previewItem;
631 webPreview.previewItem = 0;
633 webPreview.parentItem = 0;
634 webPreview.url = QString();
635 webPreview.urlRect = QRectF();