1 /***************************************************************************
2 * Copyright (C) 2005-09 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>
24 #include <QGraphicsSceneMouseEvent>
26 #include <QPersistentModelIndex>
31 #include "chatlinemodelitem.h"
32 #include "chatscene.h"
35 #include "clientbacklogmanager.h"
36 #include "columnhandleitem.h"
37 #include "iconloader.h"
38 #include "messagefilter.h"
40 #include "qtuistyle.h"
41 #include "chatviewsettings.h"
42 #include "webpreviewitem.h"
44 const qreal minContentsWidth = 200;
46 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
47 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
51 _singleBufferId(BufferId()),
52 _sceneRect(0, 0, width, 0),
55 _cutoffMode(CutoffRight),
61 _leftButtonPressed(false)
63 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
64 if(filter && filter->isSingleBufferFilter()) {
65 _singleBufferId = filter->singleBufferId();
68 ChatViewSettings defaultSettings;
69 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
70 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
72 ChatViewSettings viewSettings(this);
73 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
74 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
76 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
77 addItem(_firstColHandle);
78 _firstColHandle->setXPos(_firstColHandlePos);
79 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
80 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
82 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
83 addItem(_secondColHandle);
84 _secondColHandle->setXPos(_secondColHandlePos);
85 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
87 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
91 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
92 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
93 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
94 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
96 if(model->rowCount() > 0)
97 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
100 webPreview.timer.setSingleShot(true);
101 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
103 _showWebPreview = defaultSettings.showWebPreview();
104 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
106 _clickTimer.setInterval(QApplication::doubleClickInterval());
107 _clickTimer.setSingleShot(true);
108 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
110 setItemIndexMethod(QGraphicsScene::NoIndex);
113 ChatScene::~ChatScene() {
116 ChatView *ChatScene::chatView() const {
120 ColumnHandleItem *ChatScene::firstColumnHandle() const {
121 return _firstColHandle;
124 ColumnHandleItem *ChatScene::secondColumnHandle() const {
125 return _secondColHandle;
128 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
129 QGraphicsItem *item = itemAt(scenePos);
130 return dynamic_cast<ChatItem *>(item);
133 bool ChatScene::containsBuffer(const BufferId &id) const {
134 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
136 return filter->containsBuffer(id);
141 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
145 // QModelIndex sidx = model()->index(start, 2);
146 // QModelIndex eidx = model()->index(end, 2);
147 // qDebug() << "rowsInserted:";
149 // QModelIndex ssidx = model()->index(start - 1, 2);
150 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
151 // << ssidx.data(Qt::DisplayRole).toString();
153 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
154 // << sidx.data(Qt::DisplayRole).toString();
155 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
156 // << eidx.data(Qt::DisplayRole).toString();
157 // if(end + 1 < model()->rowCount()) {
158 // QModelIndex eeidx = model()->index(end + 1, 2);
159 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
160 // << eeidx.data(Qt::DisplayRole).toString();
165 qreal width = _sceneRect.width();
166 bool atBottom = (start == _lines.count());
167 bool atTop = !atBottom && (start == 0);
168 bool moveTop = false;
170 if(start < _lines.count()) {
171 y = _lines.value(start)->y();
172 } else if(atBottom && !_lines.isEmpty()) {
173 y = _lines.last()->y() + _lines.last()->height();
176 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
177 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
178 qreal timestampWidth = firstColumnHandle()->sceneLeft();
179 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
180 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
183 for(int i = end; i >= start; i--) {
184 ChatLine *line = new ChatLine(i, model(),
186 timestampWidth, senderWidth, contentsWidth,
187 senderPos, contentsPos);
189 line->setPos(0, y-h);
190 _lines.insert(start, line);
194 for(int i = start; i <= end; i++) {
195 ChatLine *line = new ChatLine(i, model(),
197 timestampWidth, senderWidth, contentsWidth,
198 senderPos, contentsPos);
199 line->setPos(0, y+h);
201 _lines.insert(i, line);
206 // update existing items
207 for(int i = end+1; i < _lines.count(); i++) {
208 _lines[i]->setRow(i);
212 if(_selectionStart >= 0) {
213 int offset = end - start + 1;
214 int oldStart = _selectionStart;
215 if(_selectionStart >= start)
216 _selectionStart += offset;
217 if(_selectionEnd >= start) {
218 _selectionEnd += offset;
219 if(_selectionStart == oldStart)
220 for(int i = start; i < start + offset; i++)
221 _lines[i]->setSelected(true);
223 if(_firstSelectionRow >= start)
224 _firstSelectionRow += offset;
227 // neither pre- or append means we have to do dirty work: move items...
229 int moveEnd = _lines.count() - 1;
231 if(!(atTop || atBottom)) {
232 // move top means: moving 0 to end (aka: end + 1)
233 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
234 if(end + 1 < _lines.count() - end - 1) {
244 for(int i = moveStart; i <= moveEnd; i++) {
246 line->setPos(0, line->pos().y() + offset);
250 // check if all went right
251 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
253 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
254 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
255 // qDebug() << "line[start - 1]:" << _lines.at(start - 1)->pos().y() << "+" << _lines.at(start - 1)->height() << "=" << _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height();
256 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
257 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
261 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
262 // if(end + 1 < _lines.count()) {
263 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
264 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
265 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
266 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
267 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
273 if(start < _firstLineRow) {
274 int prevFirstLineRow = _firstLineRow + (end - start + 1);
275 for(int i = end + 1; i < prevFirstLineRow; i++) {
276 _lines.at(i)->show();
279 // force new search for first proper line
283 if(atBottom || (!atTop && !moveTop)) {
284 emit lastLineChanged(_lines.last(), h);
288 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
291 qreal h = 0; // total height of removed items;
293 bool atTop = (start == 0);
294 bool atBottom = (end == _lines.count() - 1);
295 bool moveTop = false;
299 int row = _selectingItem->row();
300 if(row >= start && row <= end)
304 // remove items from scene
305 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
306 int lineCount = start;
307 while(lineIter != _lines.end() && lineCount <= end) {
308 h += (*lineIter)->height();
310 lineIter = _lines.erase(lineIter);
314 // update rows of remaining chatlines
315 for(int i = start; i < _lines.count(); i++) {
316 _lines.at(i)->setRow(i);
320 if(_selectionStart >= 0) {
321 int offset = end - start + 1;
322 if(_selectionStart >= start)
323 _selectionStart = qMax(_selectionStart -= offset, start);
324 if(_selectionEnd >= start)
325 _selectionEnd -= offset;
326 if(_firstSelectionRow >= start)
327 _firstSelectionRow -= offset;
329 if(_selectionEnd < _selectionStart) {
330 _isSelecting = false;
331 _selectionStart = -1;
335 // neither removing at bottom or top means we have to move items...
336 if(!(atTop || atBottom)) {
339 int moveEnd = _lines.count() - 1;
340 if(start < _lines.count() - start) {
350 for(int i = moveStart; i <= moveEnd; i++) {
352 line->setPos(0, line->pos().y() + offset);
356 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
359 // when searching for the first non-date-line we have to take into account that our
360 // model still contains the just removed lines so we cannot simply call updateSceneRect()
361 int numRows = model()->rowCount();
362 QModelIndex firstLineIdx;
364 bool needOffset = false;
367 if(_firstLineRow >= start && _firstLineRow <= end) {
368 _firstLineRow = end + 1;
371 firstLineIdx = model()->index(_firstLineRow, 0);
372 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
375 _firstLineRow -= end - start + 1;
379 void ChatScene::updateForViewport(qreal width, qreal height) {
380 _viewportHeight = height;
384 void ChatScene::setWidth(qreal width) {
385 if(width == _sceneRect.width())
388 // clock_t startT = clock();
390 // disabling the index while doing this complex updates is about
391 // 2 to 10 times faster!
392 //setItemIndexMethod(QGraphicsScene::NoIndex);
394 QList<ChatLine *>::iterator lineIter = _lines.end();
395 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
396 qreal linePos = _sceneRect.y() + _sceneRect.height();
397 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
398 while(lineIter != lineIterBegin) {
400 (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
402 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
404 updateSceneRect(width);
406 emit layoutChanged();
408 // clock_t endT = clock();
409 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
412 void ChatScene::firstHandlePositionChanged(qreal xpos) {
413 if(_firstColHandlePos == xpos)
416 _firstColHandlePos = xpos;
417 ChatViewSettings viewSettings(this);
418 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
419 ChatViewSettings defaultSettings;
420 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
422 // clock_t startT = clock();
424 // disabling the index while doing this complex updates is about
425 // 2 to 10 times faster!
426 //setItemIndexMethod(QGraphicsScene::NoIndex);
428 QList<ChatLine *>::iterator lineIter = _lines.end();
429 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
430 qreal timestampWidth = firstColumnHandle()->sceneLeft();
431 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
432 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
434 while(lineIter != lineIterBegin) {
436 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
438 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
442 // clock_t endT = clock();
443 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
446 void ChatScene::secondHandlePositionChanged(qreal xpos) {
447 if(_secondColHandlePos == xpos)
450 _secondColHandlePos = xpos;
451 ChatViewSettings viewSettings(this);
452 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
453 ChatViewSettings defaultSettings;
454 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
456 // clock_t startT = clock();
458 // disabling the index while doing this complex updates is about
459 // 2 to 10 times faster!
460 //setItemIndexMethod(QGraphicsScene::NoIndex);
462 QList<ChatLine *>::iterator lineIter = _lines.end();
463 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
464 qreal linePos = _sceneRect.y() + _sceneRect.height();
465 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
466 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
467 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
468 while(lineIter != lineIterBegin) {
470 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
472 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
476 emit layoutChanged();
478 // clock_t endT = clock();
479 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
482 void ChatScene::setHandleXLimits() {
483 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
484 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
487 void ChatScene::setSelectingItem(ChatItem *item) {
488 if(_selectingItem) _selectingItem->clearSelection();
489 _selectingItem = item;
492 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
493 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
494 _selectionStartCol = _selectionMinCol = item->column();
496 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
497 updateSelection(item->mapToScene(itemPos));
500 void ChatScene::updateSelection(const QPointF &pos) {
501 int curRow = rowByScenePos(pos);
502 if(curRow < 0) return;
503 int curColumn = (int)columnByScenePos(pos);
504 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
505 if(minColumn != _selectionMinCol) {
506 _selectionMinCol = minColumn;
507 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
508 _lines[l]->setSelected(true, minColumn);
511 int newstart = qMin(curRow, _firstSelectionRow);
512 int newend = qMax(curRow, _firstSelectionRow);
513 if(newstart < _selectionStart) {
514 for(int l = newstart; l < _selectionStart; l++)
515 _lines[l]->setSelected(true, minColumn);
517 if(newstart > _selectionStart) {
518 for(int l = _selectionStart; l < newstart; l++)
519 _lines[l]->setSelected(false);
521 if(newend > _selectionEnd) {
522 for(int l = _selectionEnd+1; l <= newend; l++)
523 _lines[l]->setSelected(true, minColumn);
525 if(newend < _selectionEnd) {
526 for(int l = newend+1; l <= _selectionEnd; l++)
527 _lines[l]->setSelected(false);
530 _selectionStart = newstart;
531 _selectionEnd = newend;
533 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
534 if(!_selectingItem) {
535 // _selectingItem has been removed already
538 _lines[curRow]->setSelected(false);
539 _isSelecting = false;
540 _selectionStart = -1;
541 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
545 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
546 ChatItem *chatItem = chatItemAt(pos);
549 if(hasGlobalSelection()) {
550 int row = chatItem->row();
551 if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
552 return columnByScenePos(pos) >= _selectionMinCol;
554 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
559 bool ChatScene::isScrollingAllowed() const {
563 // TODO: Handle clicks and single-item selections too
568 /******** MOUSE HANDLING **************************************************************************/
570 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
571 QPointF pos = event->scenePos();
574 // zoom actions and similar
575 chatView()->addActionsToMenu(&menu, pos);
578 if(isPosOverSelection(pos))
579 menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
580 this, SLOT(selectionToClipboard()),
583 // item-specific options (select link etc)
584 ChatItem *item = chatItemAt(pos);
586 item->addActionsToMenu(&menu, item->mapFromScene(pos));
588 // no item -> default scene actions
589 Client::mainUi()->actionProvider()->addActions(&menu, filter(), BufferId());
591 menu.exec(event->screenPos());
595 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
596 if(event->buttons() == Qt::LeftButton) {
597 if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
598 if(_clickTimer.isActive())
600 if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
601 initiateDrag(event->widget());
603 _clickMode = DragStartClick;
604 handleClick(Qt::LeftButton, _clickPos);
606 _clickMode = NoClick;
609 updateSelection(event->scenePos());
610 emit mouseMoveWhileSelecting(event->scenePos());
612 } else if(_clickHandled && _clickMode < DoubleClick)
613 QGraphicsScene::mouseMoveEvent(event);
615 QGraphicsScene::mouseMoveEvent(event);
618 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
619 if(event->buttons() == Qt::LeftButton) {
620 _leftButtonPressed = true;
621 _clickHandled = false;
622 if(!isPosOverSelection(event->scenePos())) {
623 // immediately clear selection if clicked outside; otherwise, wait for potential drag
626 if(_clickMode != NoClick && _clickTimer.isActive()) {
628 case NoClick: _clickMode = SingleClick; break;
629 case SingleClick: _clickMode = DoubleClick; break;
630 case DoubleClick: _clickMode = TripleClick; break;
631 case TripleClick: _clickMode = DoubleClick; break;
632 case DragStartClick: break;
634 handleClick(Qt::LeftButton, _clickPos);
636 _clickMode = SingleClick;
637 _clickPos = event->scenePos();
641 if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
642 QGraphicsScene::mouseDoubleClickEvent(event);
644 QGraphicsScene::mousePressEvent(event);
647 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
648 // we check for doubleclick ourselves, so just call press handler
649 mousePressEvent(event);
652 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
653 if(event->button() == Qt::LeftButton && _leftButtonPressed) {
654 _leftButtonPressed = false;
655 if(_clickMode != NoClick) {
656 if(_clickMode == SingleClick)
659 if(!_clickTimer.isActive())
660 handleClick(Qt::LeftButton, _clickPos);
662 // no click -> drag or selection move
663 if(isGloballySelecting()) {
664 selectionToClipboard(QClipboard::Selection);
665 _isSelecting = false;
671 QGraphicsScene::mouseReleaseEvent(event);
674 void ChatScene::clickTimeout() {
675 if(!_leftButtonPressed && _clickMode == SingleClick)
676 handleClick(Qt::LeftButton, _clickPos);
679 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
680 if(button == Qt::LeftButton) {
683 // Now send click down to items
684 ChatItem *chatItem = chatItemAt(scenePos);
686 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
688 _clickHandled = true;
692 void ChatScene::initiateDrag(QWidget *source) {
693 QDrag *drag = new QDrag(source);
694 QMimeData *mimeData = new QMimeData;
695 mimeData->setText(selection());
696 drag->setMimeData(mimeData);
698 drag->exec(Qt::CopyAction);
701 /******** SELECTIONS ******************************************************************************/
703 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
707 stringToClipboard(selection(), mode);
710 void ChatScene::stringToClipboard(const QString &str, QClipboard::Mode mode) {
712 case QClipboard::Clipboard:
713 QApplication::clipboard()->setText(str);
715 case QClipboard::Selection:
716 if(QApplication::clipboard()->supportsSelection())
717 QApplication::clipboard()->setText(str, QClipboard::Selection);
724 //!\brief Convert current selection to human-readable string.
725 QString ChatScene::selection() const {
726 //TODO Make selection format configurable!
727 if(hasGlobalSelection()) {
728 int start = qMin(_selectionStart, _selectionEnd);
729 int end = qMax(_selectionStart, _selectionEnd);
730 if(start < 0 || end >= _lines.count()) {
731 qDebug() << "Invalid selection range:" << start << end;
735 for(int l = start; l <= end; l++) {
736 if(_selectionMinCol == ChatLineModel::TimestampColumn)
737 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
738 if(_selectionMinCol <= ChatLineModel::SenderColumn)
739 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
740 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
743 } else if(selectingItem())
744 return selectingItem()->selection();
748 bool ChatScene::hasSelection() const {
749 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
752 bool ChatScene::hasGlobalSelection() const {
753 return _selectionStart >= 0;
756 bool ChatScene::isGloballySelecting() const {
760 void ChatScene::clearGlobalSelection() {
761 if(hasGlobalSelection()) {
762 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
763 _lines[l]->setSelected(false);
764 _isSelecting = false;
765 _selectionStart = -1;
769 void ChatScene::clearSelection() {
770 clearGlobalSelection();
772 selectingItem()->clearSelection();
775 /******** *************************************************************************************/
777 void ChatScene::requestBacklog() {
778 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
780 return filter->requestBacklog();
784 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const {
785 if(x < _firstColHandle->x())
786 return ChatLineModel::TimestampColumn;
787 if(x < _secondColHandle->x())
788 return ChatLineModel::SenderColumn;
790 return ChatLineModel::ContentsColumn;
793 int ChatScene::rowByScenePos(qreal y) const {
794 // This is somewhat hacky... we look at the contents item that is at the given y position, since
795 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
796 // ChatItems cover their ChatLine, so we won't get to the latter directly.
797 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, y)));
798 if(!contentItem) return -1;
799 return contentItem->row();
802 void ChatScene::updateSceneRect(qreal width) {
803 if(_lines.isEmpty()) {
804 updateSceneRect(QRectF(0, 0, width, 0));
808 // we hide day change messages at the top by making the scene rect smaller
809 // and by calling QGraphicsItem::hide() on all leading day change messages
810 // the first one is needed to ensure proper scrollbar ranges
811 // the second for cases where the viewport is larger then the set scenerect
812 // (in this case the items are shown anyways)
813 if(_firstLineRow == -1) {
814 int numRows = model()->rowCount();
816 QModelIndex firstLineIdx;
817 while(_firstLineRow < numRows) {
818 firstLineIdx = model()->index(_firstLineRow, 0);
819 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
821 _lines.at(_firstLineRow)->hide();
826 // the following call should be safe. If it crashes something went wrong during insert/remove
827 if(_firstLineRow < _lines.count()) {
828 ChatLine *firstLine = _lines.at(_firstLineRow);
829 ChatLine *lastLine = _lines.last();
830 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
833 updateSceneRect(QRectF(0, 0, width, 0));
837 void ChatScene::updateSceneRect(const QRectF &rect) {
843 bool ChatScene::event(QEvent *e) {
844 if(e->type() == QEvent::ApplicationPaletteChange) {
845 _firstColHandle->setColor(QApplication::palette().windowText().color());
846 _secondColHandle->setColor(QApplication::palette().windowText().color());
848 return QGraphicsScene::event(e);
851 // ========================================
853 // ========================================
855 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
859 if(webPreview.urlRect != urlRect)
860 webPreview.urlRect = urlRect;
862 if(webPreview.parentItem != parentItem)
863 webPreview.parentItem = parentItem;
865 if(webPreview.url != url) {
866 webPreview.url = url;
867 // prepare to load a different URL
868 if(webPreview.previewItem) {
869 if(webPreview.previewItem->scene())
870 removeItem(webPreview.previewItem);
871 delete webPreview.previewItem;
872 webPreview.previewItem = 0;
874 webPreview.previewState = WebPreview::NoPreview;
877 if(webPreview.url.isEmpty())
880 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
881 switch(webPreview.previewState) {
882 case WebPreview::NoPreview:
883 webPreview.previewState = WebPreview::NewPreview;
884 webPreview.timer.start(500);
886 case WebPreview::NewPreview:
887 case WebPreview::DelayPreview:
888 case WebPreview::ShowPreview:
889 // we're already waiting for the next step or showing the preview
891 case WebPreview::HidePreview:
892 // we still have a valid preview
893 webPreview.previewState = WebPreview::DelayPreview;
894 webPreview.timer.start(1000);
897 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
900 void ChatScene::webPreviewNextStep() {
901 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
902 switch(webPreview.previewState) {
903 case WebPreview::NoPreview:
905 case WebPreview::NewPreview:
906 Q_ASSERT(!webPreview.previewItem);
907 webPreview.previewItem = new WebPreviewItem(webPreview.url);
908 webPreview.previewState = WebPreview::DelayPreview;
909 webPreview.timer.start(1000);
911 case WebPreview::DelayPreview:
912 Q_ASSERT(webPreview.previewItem);
913 // calc position and show
915 qreal previewY = webPreview.urlRect.bottom();
916 qreal previewX = webPreview.urlRect.x();
917 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
918 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
920 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
921 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
923 webPreview.previewItem->setPos(previewX, previewY);
925 addItem(webPreview.previewItem);
926 webPreview.previewState = WebPreview::ShowPreview;
928 case WebPreview::ShowPreview:
929 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
930 qWarning() << "removing preview";
931 if(webPreview.previewItem && webPreview.previewItem->scene())
932 removeItem(webPreview.previewItem);
933 // Fall through to deletion!
934 case WebPreview::HidePreview:
935 if(webPreview.previewItem) {
936 delete webPreview.previewItem;
937 webPreview.previewItem = 0;
939 webPreview.parentItem = 0;
940 webPreview.url = QString();
941 webPreview.urlRect = QRectF();
942 webPreview.previewState = WebPreview::NoPreview;
944 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
947 void ChatScene::clearWebPreview(ChatItem *parentItem) {
948 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
949 switch(webPreview.previewState) {
950 case WebPreview::NewPreview:
951 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
953 case WebPreview::ShowPreview:
954 if(parentItem == 0 || webPreview.parentItem == parentItem) {
955 if(webPreview.previewItem && webPreview.previewItem->scene())
956 removeItem(webPreview.previewItem);
958 // fall through into to set hidden state
959 case WebPreview::DelayPreview:
960 // we're just loading, so haven't shown the preview yet.
961 webPreview.previewState = WebPreview::HidePreview;
962 webPreview.timer.start(5000);
964 case WebPreview::NoPreview:
965 case WebPreview::HidePreview:
968 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
972 // ========================================
973 // end of webkit only
974 // ========================================
976 void ChatScene::showWebPreviewChanged() {
977 ChatViewSettings settings;
978 _showWebPreview = settings.showWebPreview();