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>
34 #include "chatlinemodelitem.h"
35 #include "chatscene.h"
38 #include "clientbacklogmanager.h"
39 #include "columnhandleitem.h"
40 #include "contextmenuactionprovider.h"
41 #include "iconloader.h"
42 #include "messagefilter.h"
44 #include "qtuistyle.h"
45 #include "chatviewsettings.h"
46 #include "webpreviewitem.h"
48 const qreal minContentsWidth = 200;
50 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
51 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
55 _singleBufferId(BufferId()),
56 _sceneRect(0, 0, width, 0),
59 _cutoffMode(CutoffRight),
65 _leftButtonPressed(false)
67 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
68 if(filter && filter->isSingleBufferFilter()) {
69 _singleBufferId = filter->singleBufferId();
72 ChatViewSettings defaultSettings;
73 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
74 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
76 ChatViewSettings viewSettings(this);
77 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
78 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
80 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
81 addItem(_firstColHandle);
82 _firstColHandle->setXPos(_firstColHandlePos);
83 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
84 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
86 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
87 addItem(_secondColHandle);
88 _secondColHandle->setXPos(_secondColHandlePos);
89 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
91 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
95 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
96 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
97 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
98 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
99 connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
101 if(model->rowCount() > 0)
102 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
105 webPreview.timer.setSingleShot(true);
106 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
108 _showWebPreview = defaultSettings.showWebPreview();
109 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
111 _clickTimer.setInterval(QApplication::doubleClickInterval());
112 _clickTimer.setSingleShot(true);
113 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
115 setItemIndexMethod(QGraphicsScene::NoIndex);
118 ChatScene::~ChatScene() {
121 ChatView *ChatScene::chatView() const {
125 ColumnHandleItem *ChatScene::firstColumnHandle() const {
126 return _firstColHandle;
129 ColumnHandleItem *ChatScene::secondColumnHandle() const {
130 return _secondColHandle;
133 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
134 QGraphicsItem *item = itemAt(scenePos);
135 return dynamic_cast<ChatItem *>(item);
138 bool ChatScene::containsBuffer(const BufferId &id) const {
139 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
141 return filter->containsBuffer(id);
146 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
150 // QModelIndex sidx = model()->index(start, 2);
151 // QModelIndex eidx = model()->index(end, 2);
152 // qDebug() << "rowsInserted:";
154 // QModelIndex ssidx = model()->index(start - 1, 2);
155 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
156 // << ssidx.data(Qt::DisplayRole).toString();
158 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
159 // << sidx.data(Qt::DisplayRole).toString();
160 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
161 // << eidx.data(Qt::DisplayRole).toString();
162 // if(end + 1 < model()->rowCount()) {
163 // QModelIndex eeidx = model()->index(end + 1, 2);
164 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
165 // << eeidx.data(Qt::DisplayRole).toString();
170 qreal width = _sceneRect.width();
171 bool atBottom = (start == _lines.count());
172 bool atTop = !atBottom && (start == 0);
173 bool moveTop = false;
175 if(start < _lines.count()) {
176 y = _lines.value(start)->y();
177 } else if(atBottom && !_lines.isEmpty()) {
178 y = _lines.last()->y() + _lines.last()->height();
181 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
182 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
183 qreal timestampWidth = firstColumnHandle()->sceneLeft();
184 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
185 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
188 for(int i = end; i >= start; i--) {
189 ChatLine *line = new ChatLine(i, model(),
191 timestampWidth, senderWidth, contentsWidth,
192 senderPos, contentsPos);
194 line->setPos(0, y-h);
195 _lines.insert(start, line);
199 for(int i = start; i <= end; i++) {
200 ChatLine *line = new ChatLine(i, model(),
202 timestampWidth, senderWidth, contentsWidth,
203 senderPos, contentsPos);
204 line->setPos(0, y+h);
206 _lines.insert(i, line);
211 // update existing items
212 for(int i = end+1; i < _lines.count(); i++) {
213 _lines[i]->setRow(i);
217 if(_selectionStart >= 0) {
218 int offset = end - start + 1;
219 int oldStart = _selectionStart;
220 if(_selectionStart >= start)
221 _selectionStart += offset;
222 if(_selectionEnd >= start) {
223 _selectionEnd += offset;
224 if(_selectionStart == oldStart)
225 for(int i = start; i < start + offset; i++)
226 _lines[i]->setSelected(true);
228 if(_firstSelectionRow >= start)
229 _firstSelectionRow += offset;
232 // neither pre- or append means we have to do dirty work: move items...
234 int moveEnd = _lines.count() - 1;
236 if(!(atTop || atBottom)) {
237 // move top means: moving 0 to end (aka: end + 1)
238 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
239 if(end + 1 < _lines.count() - end - 1) {
249 for(int i = moveStart; i <= moveEnd; i++) {
251 line->setPos(0, line->pos().y() + offset);
255 // check if all went right
256 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
258 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
259 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
260 // 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();
261 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
262 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
266 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
267 // if(end + 1 < _lines.count()) {
268 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
269 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
270 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
271 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
272 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
278 if(start < _firstLineRow) {
279 int prevFirstLineRow = _firstLineRow + (end - start + 1);
280 for(int i = end + 1; i < prevFirstLineRow; i++) {
281 _lines.at(i)->show();
284 // force new search for first proper line
288 if(atBottom || (!atTop && !moveTop)) {
289 emit lastLineChanged(_lines.last(), h);
293 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
296 qreal h = 0; // total height of removed items;
298 bool atTop = (start == 0);
299 bool atBottom = (end == _lines.count() - 1);
300 bool moveTop = false;
304 int row = _selectingItem->row();
305 if(row >= start && row <= end)
309 // remove items from scene
310 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
311 int lineCount = start;
312 while(lineIter != _lines.end() && lineCount <= end) {
313 h += (*lineIter)->height();
315 lineIter = _lines.erase(lineIter);
319 // update rows of remaining chatlines
320 for(int i = start; i < _lines.count(); i++) {
321 _lines.at(i)->setRow(i);
325 if(_selectionStart >= 0) {
326 int offset = end - start + 1;
327 if(_selectionStart >= start)
328 _selectionStart = qMax(_selectionStart -= offset, start);
329 if(_selectionEnd >= start)
330 _selectionEnd -= offset;
331 if(_firstSelectionRow >= start)
332 _firstSelectionRow -= offset;
334 if(_selectionEnd < _selectionStart) {
335 _isSelecting = false;
336 _selectionStart = -1;
340 // neither removing at bottom or top means we have to move items...
341 if(!(atTop || atBottom)) {
344 int moveEnd = _lines.count() - 1;
345 if(start < _lines.count() - start) {
355 for(int i = moveStart; i <= moveEnd; i++) {
357 line->setPos(0, line->pos().y() + offset);
361 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
364 // when searching for the first non-date-line we have to take into account that our
365 // model still contains the just removed lines so we cannot simply call updateSceneRect()
366 int numRows = model()->rowCount();
367 QModelIndex firstLineIdx;
369 bool needOffset = false;
372 if(_firstLineRow >= start && _firstLineRow <= end) {
373 _firstLineRow = end + 1;
376 firstLineIdx = model()->index(_firstLineRow, 0);
377 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
380 _firstLineRow -= end - start + 1;
384 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br) {
385 layout(tl.row(), br.row(), _sceneRect.width());
388 void ChatScene::updateForViewport(qreal width, qreal height) {
389 _viewportHeight = height;
393 void ChatScene::setWidth(qreal width) {
394 if(width == _sceneRect.width())
396 layout(0, _lines.count()-1, width);
399 void ChatScene::layout(int start, int end, qreal width) {
400 // clock_t startT = clock();
402 // disabling the index while doing this complex updates is about
403 // 2 to 10 times faster!
404 //setItemIndexMethod(QGraphicsScene::NoIndex);
408 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
409 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
410 while(row >= start) {
411 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
415 // remaining items don't need geometry changes, but maybe repositioning?
416 ChatLine *line = _lines.at(row);
417 qreal offset = linePos - (line->scenePos().y() + line->height());
420 line = _lines.at(row--);
421 line->setPos(0, line->scenePos().y() + offset);
427 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
429 updateSceneRect(width);
431 emit layoutChanged();
433 // clock_t endT = clock();
434 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
437 void ChatScene::firstHandlePositionChanged(qreal xpos) {
438 if(_firstColHandlePos == xpos)
441 _firstColHandlePos = xpos >= 0 ? xpos : 0;
442 ChatViewSettings viewSettings(this);
443 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
444 ChatViewSettings defaultSettings;
445 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
447 // clock_t startT = clock();
449 // disabling the index while doing this complex updates is about
450 // 2 to 10 times faster!
451 //setItemIndexMethod(QGraphicsScene::NoIndex);
453 QList<ChatLine *>::iterator lineIter = _lines.end();
454 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
455 qreal timestampWidth = firstColumnHandle()->sceneLeft();
456 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
457 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
459 while(lineIter != lineIterBegin) {
461 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
463 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
467 // clock_t endT = clock();
468 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
471 void ChatScene::secondHandlePositionChanged(qreal xpos) {
472 if(_secondColHandlePos == xpos)
475 _secondColHandlePos = xpos;
476 ChatViewSettings viewSettings(this);
477 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
478 ChatViewSettings defaultSettings;
479 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
481 // clock_t startT = clock();
483 // disabling the index while doing this complex updates is about
484 // 2 to 10 times faster!
485 //setItemIndexMethod(QGraphicsScene::NoIndex);
487 QList<ChatLine *>::iterator lineIter = _lines.end();
488 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
489 qreal linePos = _sceneRect.y() + _sceneRect.height();
490 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
491 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
492 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
493 while(lineIter != lineIterBegin) {
495 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
497 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
501 emit layoutChanged();
503 // clock_t endT = clock();
504 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
507 void ChatScene::setHandleXLimits() {
508 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
509 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
512 void ChatScene::setSelectingItem(ChatItem *item) {
513 if(_selectingItem) _selectingItem->clearSelection();
514 _selectingItem = item;
517 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
518 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
519 _selectionStartCol = _selectionMinCol = item->column();
521 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
522 updateSelection(item->mapToScene(itemPos));
525 void ChatScene::updateSelection(const QPointF &pos) {
526 int curRow = rowByScenePos(pos);
527 if(curRow < 0) return;
528 int curColumn = (int)columnByScenePos(pos);
529 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
530 if(minColumn != _selectionMinCol) {
531 _selectionMinCol = minColumn;
532 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
533 _lines[l]->setSelected(true, minColumn);
536 int newstart = qMin(curRow, _firstSelectionRow);
537 int newend = qMax(curRow, _firstSelectionRow);
538 if(newstart < _selectionStart) {
539 for(int l = newstart; l < _selectionStart; l++)
540 _lines[l]->setSelected(true, minColumn);
542 if(newstart > _selectionStart) {
543 for(int l = _selectionStart; l < newstart; l++)
544 _lines[l]->setSelected(false);
546 if(newend > _selectionEnd) {
547 for(int l = _selectionEnd+1; l <= newend; l++)
548 _lines[l]->setSelected(true, minColumn);
550 if(newend < _selectionEnd) {
551 for(int l = newend+1; l <= _selectionEnd; l++)
552 _lines[l]->setSelected(false);
555 _selectionStart = newstart;
556 _selectionEnd = newend;
558 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
559 if(!_selectingItem) {
560 // _selectingItem has been removed already
563 _lines[curRow]->setSelected(false);
564 _isSelecting = false;
565 _selectionStart = -1;
566 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
570 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
571 ChatItem *chatItem = chatItemAt(pos);
574 if(hasGlobalSelection()) {
575 int row = chatItem->row();
576 if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
577 return columnByScenePos(pos) >= _selectionMinCol;
579 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
584 bool ChatScene::isScrollingAllowed() const {
588 // TODO: Handle clicks and single-item selections too
593 /******** MOUSE HANDLING **************************************************************************/
595 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
596 QPointF pos = event->scenePos();
599 // zoom actions and similar
600 chatView()->addActionsToMenu(&menu, pos);
603 if(isPosOverSelection(pos))
604 menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
605 this, SLOT(selectionToClipboard()),
608 // item-specific options (select link etc)
609 ChatItem *item = chatItemAt(pos);
611 item->addActionsToMenu(&menu, item->mapFromScene(pos));
613 // no item -> default scene actions
614 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
616 menu.exec(event->screenPos());
620 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
621 if(event->buttons() == Qt::LeftButton) {
622 if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
623 if(_clickTimer.isActive())
625 if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
626 initiateDrag(event->widget());
628 _clickMode = DragStartClick;
629 handleClick(Qt::LeftButton, _clickPos);
631 _clickMode = NoClick;
634 updateSelection(event->scenePos());
635 emit mouseMoveWhileSelecting(event->scenePos());
637 } else if(_clickHandled && _clickMode < DoubleClick)
638 QGraphicsScene::mouseMoveEvent(event);
640 QGraphicsScene::mouseMoveEvent(event);
643 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
644 if(event->buttons() == Qt::LeftButton) {
645 _leftButtonPressed = true;
646 _clickHandled = false;
647 if(!isPosOverSelection(event->scenePos())) {
648 // immediately clear selection if clicked outside; otherwise, wait for potential drag
651 if(_clickMode != NoClick && _clickTimer.isActive()) {
653 case NoClick: _clickMode = SingleClick; break;
654 case SingleClick: _clickMode = DoubleClick; break;
655 case DoubleClick: _clickMode = TripleClick; break;
656 case TripleClick: _clickMode = DoubleClick; break;
657 case DragStartClick: break;
659 handleClick(Qt::LeftButton, _clickPos);
661 _clickMode = SingleClick;
662 _clickPos = event->scenePos();
666 if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
667 QGraphicsScene::mouseDoubleClickEvent(event);
669 QGraphicsScene::mousePressEvent(event);
672 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
673 // we check for doubleclick ourselves, so just call press handler
674 mousePressEvent(event);
677 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
678 if(event->button() == Qt::LeftButton && _leftButtonPressed) {
679 _leftButtonPressed = false;
680 if(_clickMode != NoClick) {
681 if(_clickMode == SingleClick)
684 if(!_clickTimer.isActive())
685 handleClick(Qt::LeftButton, _clickPos);
687 // no click -> drag or selection move
688 if(isGloballySelecting()) {
689 selectionToClipboard(QClipboard::Selection);
690 _isSelecting = false;
696 QGraphicsScene::mouseReleaseEvent(event);
699 void ChatScene::clickTimeout() {
700 if(!_leftButtonPressed && _clickMode == SingleClick)
701 handleClick(Qt::LeftButton, _clickPos);
704 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
705 if(button == Qt::LeftButton) {
708 // Now send click down to items
709 ChatItem *chatItem = chatItemAt(scenePos);
711 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
713 _clickHandled = true;
717 void ChatScene::initiateDrag(QWidget *source) {
718 QDrag *drag = new QDrag(source);
719 QMimeData *mimeData = new QMimeData;
720 mimeData->setText(selection());
721 drag->setMimeData(mimeData);
723 drag->exec(Qt::CopyAction);
726 /******** SELECTIONS ******************************************************************************/
728 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
732 stringToClipboard(selection(), mode);
735 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode) {
737 // remove trailing linefeeds
738 if(str.endsWith('\n'))
742 case QClipboard::Clipboard:
743 QApplication::clipboard()->setText(str);
745 case QClipboard::Selection:
746 if(QApplication::clipboard()->supportsSelection())
747 QApplication::clipboard()->setText(str, QClipboard::Selection);
754 //!\brief Convert current selection to human-readable string.
755 QString ChatScene::selection() const {
756 //TODO Make selection format configurable!
757 if(hasGlobalSelection()) {
758 int start = qMin(_selectionStart, _selectionEnd);
759 int end = qMax(_selectionStart, _selectionEnd);
760 if(start < 0 || end >= _lines.count()) {
761 qDebug() << "Invalid selection range:" << start << end;
765 for(int l = start; l <= end; l++) {
766 if(_selectionMinCol == ChatLineModel::TimestampColumn)
767 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
768 if(_selectionMinCol <= ChatLineModel::SenderColumn)
769 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
770 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
773 } else if(selectingItem())
774 return selectingItem()->selection();
778 bool ChatScene::hasSelection() const {
779 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
782 bool ChatScene::hasGlobalSelection() const {
783 return _selectionStart >= 0;
786 bool ChatScene::isGloballySelecting() const {
790 void ChatScene::clearGlobalSelection() {
791 if(hasGlobalSelection()) {
792 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
793 _lines[l]->setSelected(false);
794 _isSelecting = false;
795 _selectionStart = -1;
799 void ChatScene::clearSelection() {
800 clearGlobalSelection();
802 selectingItem()->clearSelection();
805 /******** *************************************************************************************/
807 void ChatScene::requestBacklog() {
808 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
810 return filter->requestBacklog();
814 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const {
815 if(x < _firstColHandle->x())
816 return ChatLineModel::TimestampColumn;
817 if(x < _secondColHandle->x())
818 return ChatLineModel::SenderColumn;
820 return ChatLineModel::ContentsColumn;
823 int ChatScene::rowByScenePos(qreal y) const {
824 // This is somewhat hacky... we look at the contents item that is at the given y position, since
825 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
826 // ChatItems cover their ChatLine, so we won't get to the latter directly.
827 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, y)));
828 if(!contentItem) return -1;
829 return contentItem->row();
832 void ChatScene::updateSceneRect(qreal width) {
833 if(_lines.isEmpty()) {
834 updateSceneRect(QRectF(0, 0, width, 0));
838 // we hide day change messages at the top by making the scene rect smaller
839 // and by calling QGraphicsItem::hide() on all leading day change messages
840 // the first one is needed to ensure proper scrollbar ranges
841 // the second for cases where the viewport is larger then the set scenerect
842 // (in this case the items are shown anyways)
843 if(_firstLineRow == -1) {
844 int numRows = model()->rowCount();
846 QModelIndex firstLineIdx;
847 while(_firstLineRow < numRows) {
848 firstLineIdx = model()->index(_firstLineRow, 0);
849 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
851 _lines.at(_firstLineRow)->hide();
856 // the following call should be safe. If it crashes something went wrong during insert/remove
857 if(_firstLineRow < _lines.count()) {
858 ChatLine *firstLine = _lines.at(_firstLineRow);
859 ChatLine *lastLine = _lines.last();
860 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
863 updateSceneRect(QRectF(0, 0, width, 0));
867 void ChatScene::updateSceneRect(const QRectF &rect) {
873 bool ChatScene::event(QEvent *e) {
874 if(e->type() == QEvent::ApplicationPaletteChange) {
875 _firstColHandle->setColor(QApplication::palette().windowText().color());
876 _secondColHandle->setColor(QApplication::palette().windowText().color());
878 return QGraphicsScene::event(e);
881 // ========================================
883 // ========================================
885 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
889 if(webPreview.urlRect != urlRect)
890 webPreview.urlRect = urlRect;
892 if(webPreview.parentItem != parentItem)
893 webPreview.parentItem = parentItem;
895 if(webPreview.url != url) {
896 webPreview.url = url;
897 // prepare to load a different URL
898 if(webPreview.previewItem) {
899 if(webPreview.previewItem->scene())
900 removeItem(webPreview.previewItem);
901 delete webPreview.previewItem;
902 webPreview.previewItem = 0;
904 webPreview.previewState = WebPreview::NoPreview;
907 if(webPreview.url.isEmpty())
910 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
911 switch(webPreview.previewState) {
912 case WebPreview::NoPreview:
913 webPreview.previewState = WebPreview::NewPreview;
914 webPreview.timer.start(500);
916 case WebPreview::NewPreview:
917 case WebPreview::DelayPreview:
918 case WebPreview::ShowPreview:
919 // we're already waiting for the next step or showing the preview
921 case WebPreview::HidePreview:
922 // we still have a valid preview
923 webPreview.previewState = WebPreview::DelayPreview;
924 webPreview.timer.start(1000);
927 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
930 void ChatScene::webPreviewNextStep() {
931 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
932 switch(webPreview.previewState) {
933 case WebPreview::NoPreview:
935 case WebPreview::NewPreview:
936 Q_ASSERT(!webPreview.previewItem);
937 webPreview.previewItem = new WebPreviewItem(webPreview.url);
938 webPreview.previewState = WebPreview::DelayPreview;
939 webPreview.timer.start(1000);
941 case WebPreview::DelayPreview:
942 Q_ASSERT(webPreview.previewItem);
943 // calc position and show
945 qreal previewY = webPreview.urlRect.bottom();
946 qreal previewX = webPreview.urlRect.x();
947 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
948 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
950 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
951 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
953 webPreview.previewItem->setPos(previewX, previewY);
955 addItem(webPreview.previewItem);
956 webPreview.previewState = WebPreview::ShowPreview;
958 case WebPreview::ShowPreview:
959 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
960 qWarning() << "removing preview";
961 if(webPreview.previewItem && webPreview.previewItem->scene())
962 removeItem(webPreview.previewItem);
963 // Fall through to deletion!
964 case WebPreview::HidePreview:
965 if(webPreview.previewItem) {
966 delete webPreview.previewItem;
967 webPreview.previewItem = 0;
969 webPreview.parentItem = 0;
970 webPreview.url = QString();
971 webPreview.urlRect = QRectF();
972 webPreview.previewState = WebPreview::NoPreview;
974 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
977 void ChatScene::clearWebPreview(ChatItem *parentItem) {
978 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
979 switch(webPreview.previewState) {
980 case WebPreview::NewPreview:
981 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
983 case WebPreview::ShowPreview:
984 if(parentItem == 0 || webPreview.parentItem == parentItem) {
985 if(webPreview.previewItem && webPreview.previewItem->scene())
986 removeItem(webPreview.previewItem);
988 // fall through into to set hidden state
989 case WebPreview::DelayPreview:
990 // we're just loading, so haven't shown the preview yet.
991 webPreview.previewState = WebPreview::HidePreview;
992 webPreview.timer.start(5000);
994 case WebPreview::NoPreview:
995 case WebPreview::HidePreview:
998 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1002 // ========================================
1003 // end of webkit only
1004 // ========================================
1006 void ChatScene::showWebPreviewChanged() {
1007 ChatViewSettings settings;
1008 _showWebPreview = settings.showWebPreview();