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 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
42 : QGraphicsScene(0, 0, width, 0, parent),
45 _singleBufferScene(false),
46 _sceneRect(0, 0, width, 0),
53 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
55 _singleBufferScene = filter->isSingleBufferFilter();
58 ChatViewSettings defaultSettings;
59 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
60 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
62 ChatViewSettings viewSettings(this);
63 firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
64 secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
66 firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
67 addItem(firstColHandle);
68 firstColHandle->setXPos(firstColHandlePos);
69 connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
70 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
72 secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
73 addItem(secondColHandle);
74 secondColHandle->setXPos(secondColHandlePos);
75 connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
76 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
80 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
81 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
82 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
83 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
85 if(model->rowCount() > 0)
86 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
89 ChatScene::~ChatScene() {
92 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
97 // QModelIndex sidx = model()->index(start, 0);
98 // QModelIndex eidx = model()->index(end, 0);
99 // qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
102 qreal y = _sceneRect.y();
103 qreal width = _sceneRect.width();
105 bool atBottom = false;
106 bool moveTop = false;
108 if(start > 0 && start < _lines.count()) {
109 y = _lines.value(start)->y();
112 if(start == _lines.count()) {
113 y = _sceneRect.bottom();
118 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
119 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
120 qreal timestampWidth = firstColumnHandle()->sceneLeft();
121 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
122 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
124 for(int i = start; i <= end; i++) {
125 ChatLine *line = new ChatLine(i, model(),
127 timestampWidth, senderWidth, contentsWidth,
128 senderPos, contentsPos);
129 line->setPos(0, y+h);
131 _lines.insert(i, line);
135 // update existing items
136 for(int i = end+1; i < _lines.count(); i++) {
137 _lines[i]->setRow(i);
141 if(_selectionStart >= 0) {
142 int offset = end - start + 1;
143 if(_selectionStart >= start) _selectionStart += offset;
144 if(_selectionEnd >= start) _selectionEnd += offset;
145 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
146 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
149 // neither pre- or append means we have to do dirty work: move items...
150 if(!(atTop || atBottom)) {
153 int moveEnd = _lines.count() - 1;
154 // move top means: moving 0 to end (aka: end + 1)
155 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
156 if(end + 1 < _lines.count() - end - 1) {
166 for(int i = moveStart; i <= moveEnd; i++) {
168 line->setPos(0, line->pos().y() + offset);
173 if(atTop || moveTop) {
174 updateSceneRect(_sceneRect.adjusted(0, -h, 0, 0));
176 updateSceneRect(_sceneRect.adjusted(0, 0, 0, h));
177 emit lastLineChanged(_lines.last());
182 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
187 qreal h = 0; // total height of removed items;
189 bool atTop = (start == 0);
190 bool atBottom = (end == _lines.count() - 1);
191 bool moveTop = false;
193 // remove items from scene
194 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
195 int lineCount = start;
196 while(lineIter != _lines.end() && lineCount <= end) {
197 h += (*lineIter)->height();
199 lineIter = _lines.erase(lineIter);
203 // update rows of remaining chatlines
204 for(int i = start; i < _lines.count(); i++) {
205 _lines.at(i)->setRow(i);
209 if(_selectionStart >= 0) {
210 int offset = end - start + 1;
211 if(_selectionStart >= start)
212 _selectionStart -= offset;
213 if(_selectionEnd >= start)
214 _selectionEnd -= offset;
215 if(_firstSelectionRow >= start)
216 _firstSelectionRow -= offset;
217 if(_lastSelectionRow >= start)
218 _lastSelectionRow -= offset;
221 // neither removing at bottom or top means we have to move items...
222 if(!(atTop || atBottom)) {
225 int moveEnd = _lines.count() - 1;
226 if(start < _lines.count() - start) {
236 for(int i = moveStart; i <= moveEnd; i++) {
238 line->setPos(0, line->pos().y() + offset);
243 if(atTop || moveTop) {
244 updateSceneRect(_sceneRect.adjusted(0, h, 0, 0));
246 updateSceneRect(_sceneRect.adjusted(0, 0, 0, -h));
250 void ChatScene::updateForViewport(qreal width, qreal height) {
251 _viewportHeight = height;
255 // setWidth is used for 2 things:
256 // a) updating the scene to fit the width of the corresponding view
257 // b) to update the positions of the items if a columhandle has changed it's position
258 // forceReposition is true in the second case
259 // this method features some codeduplication for the sake of performance
260 void ChatScene::setWidth(qreal width, bool forceReposition) {
261 if(width == _sceneRect.width() && !forceReposition)
264 // clock_t startT = clock();
266 qreal linePos = _sceneRect.y() + _sceneRect.height();
267 qreal yBottom = linePos;
268 QList<ChatLine *>::iterator lineIter = _lines.end();
269 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
271 qreal lineHeight = 0;
272 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
274 if(forceReposition) {
275 qreal timestampWidth = firstColumnHandle()->sceneLeft();
276 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
277 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
278 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
279 while(lineIter != lineIterBegin) {
282 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
283 linePos -= lineHeight;
284 line->setPos(0, linePos);
287 while(lineIter != lineIterBegin) {
290 lineHeight = line->setGeometryByWidth(width, contentsWidth);
291 linePos -= lineHeight;
292 line->setPos(0, linePos);
296 updateSceneRect(QRectF(0, linePos, width, yBottom - linePos));
299 // clock_t endT = clock();
300 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
303 void ChatScene::handlePositionChanged(qreal xpos) {
304 bool first = (sender() == firstColHandle);
307 oldx = firstColHandlePos;
308 firstColHandlePos = xpos;
310 oldx = secondColHandlePos;
311 secondColHandlePos = xpos;
314 ChatViewSettings viewSettings(this);
315 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
316 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
318 ChatViewSettings defaultSettings;
319 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
320 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
322 setWidth(width(), true); // readjust all chatlines
323 // we get ugly redraw errors if we don't update this explicitly... :(
324 // width() should be the same for both handles, so just use firstColHandle regardless
325 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
328 void ChatScene::setHandleXLimits() {
329 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
330 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
333 void ChatScene::setSelectingItem(ChatItem *item) {
334 if(_selectingItem) _selectingItem->clearSelection();
335 _selectingItem = item;
338 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
339 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
340 _selectionStartCol = _selectionMinCol = item->column();
342 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
343 updateSelection(item->mapToScene(itemPos));
346 void ChatScene::updateSelection(const QPointF &pos) {
347 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
348 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
349 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
350 if(!contentItem) return;
352 int curRow = contentItem->row();
354 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
355 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
356 else curColumn = ChatLineModel::TimestampColumn;
358 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
359 if(minColumn != _selectionMinCol) {
360 _selectionMinCol = minColumn;
361 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
362 _lines[l]->setSelected(true, minColumn);
365 int newstart = qMin(curRow, _firstSelectionRow);
366 int newend = qMax(curRow, _firstSelectionRow);
367 if(newstart < _selectionStart) {
368 for(int l = newstart; l < _selectionStart; l++)
369 _lines[l]->setSelected(true, minColumn);
371 if(newstart > _selectionStart) {
372 for(int l = _selectionStart; l < newstart; l++)
373 _lines[l]->setSelected(false);
375 if(newend > _selectionEnd) {
376 for(int l = _selectionEnd+1; l <= newend; l++)
377 _lines[l]->setSelected(true, minColumn);
379 if(newend < _selectionEnd) {
380 for(int l = newend+1; l <= _selectionEnd; l++)
381 _lines[l]->setSelected(false);
384 _selectionStart = newstart;
385 _selectionEnd = newend;
386 _lastSelectionRow = curRow;
388 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
389 if(!_selectingItem) {
390 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
393 _lines[curRow]->setSelected(false);
394 _isSelecting = false;
395 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
399 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
400 if(_isSelecting && event->buttons() == Qt::LeftButton) {
401 updateSelection(event->scenePos());
404 QGraphicsScene::mouseMoveEvent(event);
408 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
409 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
410 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
411 _lines[l]->setSelected(false);
413 _selectionStart = -1;
414 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
416 QGraphicsScene::mousePressEvent(event);
420 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
421 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
422 putToClipboard(selectionToString());
423 _isSelecting = false;
426 QGraphicsScene::mouseReleaseEvent(event);
430 void ChatScene::putToClipboard(const QString &selection) {
431 // TODO Configure clipboards
433 QApplication::clipboard()->setText(selection, QClipboard::Selection);
436 QApplication::clipboard()->setText(selection);
440 //!\brief Convert current selection to human-readable string.
441 QString ChatScene::selectionToString() const {
442 //TODO Make selection format configurable!
443 if(!_isSelecting) return QString();
444 int start = qMin(_selectionStart, _selectionEnd);
445 int end = qMax(_selectionStart, _selectionEnd);
446 if(start < 0 || end >= _lines.count()) {
447 qDebug() << "Invalid selection range:" << start << end;
451 for(int l = start; l <= end; l++) {
452 if(_selectionMinCol == ChatLineModel::TimestampColumn)
453 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
454 if(_selectionMinCol <= ChatLineModel::SenderColumn)
455 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
456 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
461 void ChatScene::requestBacklog() {
462 static const int REQUEST_COUNT = 500;
463 int backlogSize = model()->rowCount();
464 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
465 QModelIndex msgIdx = model()->index(0, 0);
466 while((Message::Type)(model()->data(msgIdx, ChatLineModel::TypeRole).toInt()) == Message::DayChange) {
467 msgIdx = msgIdx.sibling(msgIdx.row() + 1, 0);
469 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
470 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
471 _lastBacklogSize = backlogSize;
472 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
476 int ChatScene::sectionByScenePos(int x) {
477 if(x < firstColHandle->x())
478 return ChatLineModel::TimestampColumn;
479 if(x < secondColHandle->x())
480 return ChatLineModel::SenderColumn;
482 return ChatLineModel::ContentsColumn;
485 void ChatScene::updateSceneRect(const QRectF &rect) {
491 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
497 if(webPreview.parentItem != parentItem)
498 webPreview.parentItem = parentItem;
500 if(webPreview.url != url) {
501 webPreview.url = url;
502 // load a new web view and delete the old one (if exists)
503 if(webPreview.previewItem) {
504 removeItem(webPreview.previewItem);
505 delete webPreview.previewItem;
507 webPreview.previewItem = new WebPreviewItem(url);
508 addItem(webPreview.previewItem);
510 if(webPreview.urlRect != urlRect) {
511 webPreview.urlRect = urlRect;
512 qreal previewY = urlRect.bottom();
513 qreal previewX = urlRect.x();
514 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
515 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
517 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
518 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
520 webPreview.previewItem->setPos(previewX, previewY);
525 void ChatScene::clearWebPreview(ChatItem *parentItem) {
529 if(parentItem == 0 || webPreview.parentItem == parentItem) {
530 if(webPreview.previewItem) {
531 removeItem(webPreview.previewItem);
532 delete webPreview.previewItem;
533 webPreview.previewItem = 0;
535 webPreview.parentItem = 0;
536 webPreview.url = QString();
537 webPreview.urlRect = QRectF();