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"
38 const qreal minContentsWidth = 200;
40 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
41 : QGraphicsScene(0, 0, width, 0, parent),
44 _singleBufferScene(false),
45 _sceneRect(0, 0, width, 0),
52 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
54 _singleBufferScene = filter->isSingleBufferFilter();
57 ChatViewSettings defaultSettings;
58 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
59 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
61 ChatViewSettings viewSettings(this);
62 firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
63 secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
65 firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
66 addItem(firstColHandle);
67 firstColHandle->setXPos(firstColHandlePos);
68 connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
69 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
71 secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
72 addItem(secondColHandle);
73 secondColHandle->setXPos(secondColHandlePos);
74 connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
75 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
79 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
80 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
81 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
82 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
84 if(model->rowCount() > 0)
85 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
88 ChatScene::~ChatScene() {
91 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
94 qreal y = _sceneRect.y();
95 qreal width = _sceneRect.width();
97 bool atBottom = false;
101 y = _lines.value(start - 1)->y() + _lines.value(start - 1)->height();
104 if(start == _lines.count())
107 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
108 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
109 qreal timestampWidth = firstColumnHandle()->sceneLeft();
110 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
111 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
114 for(int i = end; i >= start; i--) {
115 ChatLine *line = new ChatLine(i, model(),
117 timestampWidth, senderWidth, contentsWidth,
118 senderPos, contentsPos);
121 line->setPos(0, y+h);
123 line->setPos(0, y+h);
126 _lines.insert(start, line);
130 // update existing items
131 for(int i = end+1; i < _lines.count(); i++) {
132 _lines[i]->setRow(i);
136 if(_selectionStart >= 0) {
137 int offset = end - start + 1;
138 if(_selectionStart >= start) _selectionStart += offset;
139 if(_selectionEnd >= start) _selectionEnd += offset;
140 if(_firstSelectionRow >= start) _firstSelectionRow += offset;
141 if(_lastSelectionRow >= start) _lastSelectionRow += offset;
144 // neither pre- or append means we have to do dirty work: move items...
145 if(!(atTop || atBottom)) {
148 int moveEnd = _lines.count() - 1;
150 if(end > _lines.count() - end) {
159 for(int i = moveStart; i <= moveEnd; i++) {
161 line->setPos(0, line->pos().y() + offset);
166 if(atTop || moveTop) {
167 updateSceneRect(_sceneRect.adjusted(0, h, 0, 0));
169 updateSceneRect(_sceneRect.adjusted(0, 0, 0, h));
170 emit lastLineChanged(_lines.last());
175 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
178 qreal h = 0; // total height of removed items;
180 bool atTop = (start == 0);
181 bool atBottom = (end == _lines.count() - 1);
182 bool moveTop = false;
184 // remove items from scene
185 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
186 int lineCount = start;
187 while(lineIter != _lines.end() && lineCount <= end) {
188 h += (*lineIter)->height();
190 lineIter = _lines.erase(lineIter);
194 // update rows of remaining chatlines
195 for(int i = start; i < _lines.count(); i++) {
196 _lines.at(i)->setRow(i);
200 if(_selectionStart >= 0) {
201 int offset = end - start + 1;
202 if(_selectionStart >= start)
203 _selectionStart -= offset;
204 if(_selectionEnd >= start)
205 _selectionEnd -= offset;
206 if(_firstSelectionRow >= start)
207 _firstSelectionRow -= offset;
208 if(_lastSelectionRow >= start)
209 _lastSelectionRow -= offset;
212 // neither removing at bottom or top means we have to move items...
213 if(!(atTop || atBottom)) {
216 int moveEnd = _lines.count() - 1;
218 if(start > _lines.count() - end) {
227 for(int i = moveStart; i <= moveEnd; i++) {
229 line->setPos(0, line->pos().y() + offset);
234 if(atTop || moveTop) {
235 updateSceneRect(_sceneRect.adjusted(0, h, 0, 0));
237 updateSceneRect(_sceneRect.adjusted(0, 0, 0, -h));
241 void ChatScene::updateForViewport(qreal width, qreal height) {
242 _viewportHeight = height;
246 // setWidth is used for 2 things:
247 // a) updating the scene to fit the width of the corresponding view
248 // b) to update the positions of the items if a columhandle has changed it's position
249 // forceReposition is true in the second case
250 // this method features some codeduplication for the sake of performance
251 void ChatScene::setWidth(qreal width, bool forceReposition) {
252 if(width == _sceneRect.width() && !forceReposition)
255 // clock_t startT = clock();
257 qreal linePos = _sceneRect.y() + _sceneRect.height();
258 qreal yBottom = linePos;
259 QList<ChatLine *>::iterator lineIter = _lines.end();
260 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
262 qreal lineHeight = 0;
263 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
265 if(forceReposition) {
266 qreal timestampWidth = firstColumnHandle()->sceneLeft();
267 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
268 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
269 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
270 while(lineIter != lineIterBegin) {
273 lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
274 linePos -= lineHeight;
275 line->setPos(0, linePos);
278 while(lineIter != lineIterBegin) {
281 lineHeight = line->setGeometryByWidth(width, contentsWidth);
282 linePos -= lineHeight;
283 line->setPos(0, linePos);
287 updateSceneRect(QRectF(0, linePos, width, yBottom - linePos));
290 // clock_t endT = clock();
291 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
294 void ChatScene::handlePositionChanged(qreal xpos) {
295 bool first = (sender() == firstColHandle);
298 oldx = firstColHandlePos;
299 firstColHandlePos = xpos;
301 oldx = secondColHandlePos;
302 secondColHandlePos = xpos;
305 ChatViewSettings viewSettings(this);
306 viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
307 viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
309 ChatViewSettings defaultSettings;
310 defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
311 defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
313 setWidth(width(), true); // readjust all chatlines
314 // we get ugly redraw errors if we don't update this explicitly... :(
315 // width() should be the same for both handles, so just use firstColHandle regardless
316 //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
319 void ChatScene::setHandleXLimits() {
320 firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
321 secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
324 void ChatScene::setSelectingItem(ChatItem *item) {
325 if(_selectingItem) _selectingItem->clearSelection();
326 _selectingItem = item;
329 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
330 _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
331 _selectionStartCol = _selectionMinCol = item->column();
333 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
334 updateSelection(item->mapToScene(itemPos));
337 void ChatScene::updateSelection(const QPointF &pos) {
338 // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
339 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
340 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
341 if(!contentItem) return;
343 int curRow = contentItem->row();
345 if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
346 else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
347 else curColumn = ChatLineModel::TimestampColumn;
349 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
350 if(minColumn != _selectionMinCol) {
351 _selectionMinCol = minColumn;
352 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
353 _lines[l]->setSelected(true, minColumn);
356 int newstart = qMin(curRow, _firstSelectionRow);
357 int newend = qMax(curRow, _firstSelectionRow);
358 if(newstart < _selectionStart) {
359 for(int l = newstart; l < _selectionStart; l++)
360 _lines[l]->setSelected(true, minColumn);
362 if(newstart > _selectionStart) {
363 for(int l = _selectionStart; l < newstart; l++)
364 _lines[l]->setSelected(false);
366 if(newend > _selectionEnd) {
367 for(int l = _selectionEnd+1; l <= newend; l++)
368 _lines[l]->setSelected(true, minColumn);
370 if(newend < _selectionEnd) {
371 for(int l = newend+1; l <= _selectionEnd; l++)
372 _lines[l]->setSelected(false);
375 _selectionStart = newstart;
376 _selectionEnd = newend;
377 _lastSelectionRow = curRow;
379 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
380 if(!_selectingItem) {
381 qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
384 _lines[curRow]->setSelected(false);
385 _isSelecting = false;
386 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
390 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
391 if(_isSelecting && event->buttons() == Qt::LeftButton) {
392 updateSelection(event->scenePos());
395 QGraphicsScene::mouseMoveEvent(event);
399 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
400 if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
401 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
402 _lines[l]->setSelected(false);
404 _selectionStart = -1;
405 QGraphicsScene::mousePressEvent(event); // so we can start a new local selection
407 QGraphicsScene::mousePressEvent(event);
411 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
412 if(_isSelecting && !event->buttons() & Qt::LeftButton) {
413 putToClipboard(selectionToString());
414 _isSelecting = false;
417 QGraphicsScene::mouseReleaseEvent(event);
421 void ChatScene::putToClipboard(const QString &selection) {
422 // TODO Configure clipboards
424 QApplication::clipboard()->setText(selection, QClipboard::Selection);
427 QApplication::clipboard()->setText(selection);
431 //!\brief Convert current selection to human-readable string.
432 QString ChatScene::selectionToString() const {
433 //TODO Make selection format configurable!
434 if(!_isSelecting) return QString();
435 int start = qMin(_selectionStart, _selectionEnd);
436 int end = qMax(_selectionStart, _selectionEnd);
437 if(start < 0 || end >= _lines.count()) {
438 qDebug() << "Invalid selection range:" << start << end;
442 for(int l = start; l <= end; l++) {
443 if(_selectionMinCol == ChatLineModel::TimestampColumn)
444 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
445 if(_selectionMinCol <= ChatLineModel::SenderColumn)
446 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
447 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
452 void ChatScene::requestBacklog() {
453 static const int REQUEST_COUNT = 500;
454 int backlogSize = model()->rowCount();
455 if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
456 QModelIndex msgIdx = model()->index(0, 0);
457 MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
458 BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
459 _lastBacklogSize = backlogSize;
460 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
464 int ChatScene::sectionByScenePos(int x) {
465 if(x < firstColHandle->x())
466 return ChatLineModel::TimestampColumn;
467 if(x < secondColHandle->x())
468 return ChatLineModel::SenderColumn;
470 return ChatLineModel::ContentsColumn;
473 void ChatScene::updateSceneRect(const QRectF &rect) {