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 // This should only be sent (currently) if the style is reloaded -> re-layout the whole scene
386 // TODO: Check range and only do partial relayouts, if appropriate
391 void ChatScene::updateForViewport(qreal width, qreal height) {
392 _viewportHeight = height;
396 void ChatScene::setWidth(qreal width) {
397 if(width == _sceneRect.width())
402 void ChatScene::layout(qreal width) {
403 // clock_t startT = clock();
406 width = _sceneRect.width();
408 // disabling the index while doing this complex updates is about
409 // 2 to 10 times faster!
410 //setItemIndexMethod(QGraphicsScene::NoIndex);
412 QList<ChatLine *>::iterator lineIter = _lines.end();
413 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
414 qreal linePos = _sceneRect.y() + _sceneRect.height();
415 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
416 while(lineIter != lineIterBegin) {
418 (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
420 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
422 updateSceneRect(width);
424 emit layoutChanged();
426 // clock_t endT = clock();
427 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
430 void ChatScene::firstHandlePositionChanged(qreal xpos) {
431 if(_firstColHandlePos == xpos)
434 _firstColHandlePos = xpos;
435 ChatViewSettings viewSettings(this);
436 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
437 ChatViewSettings defaultSettings;
438 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
440 // clock_t startT = clock();
442 // disabling the index while doing this complex updates is about
443 // 2 to 10 times faster!
444 //setItemIndexMethod(QGraphicsScene::NoIndex);
446 QList<ChatLine *>::iterator lineIter = _lines.end();
447 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
448 qreal timestampWidth = firstColumnHandle()->sceneLeft();
449 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
450 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
452 while(lineIter != lineIterBegin) {
454 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
456 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
460 // clock_t endT = clock();
461 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
464 void ChatScene::secondHandlePositionChanged(qreal xpos) {
465 if(_secondColHandlePos == xpos)
468 _secondColHandlePos = xpos;
469 ChatViewSettings viewSettings(this);
470 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
471 ChatViewSettings defaultSettings;
472 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
474 // clock_t startT = clock();
476 // disabling the index while doing this complex updates is about
477 // 2 to 10 times faster!
478 //setItemIndexMethod(QGraphicsScene::NoIndex);
480 QList<ChatLine *>::iterator lineIter = _lines.end();
481 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
482 qreal linePos = _sceneRect.y() + _sceneRect.height();
483 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
484 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
485 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
486 while(lineIter != lineIterBegin) {
488 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
490 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
494 emit layoutChanged();
496 // clock_t endT = clock();
497 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
500 void ChatScene::setHandleXLimits() {
501 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
502 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
505 void ChatScene::setSelectingItem(ChatItem *item) {
506 if(_selectingItem) _selectingItem->clearSelection();
507 _selectingItem = item;
510 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
511 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
512 _selectionStartCol = _selectionMinCol = item->column();
514 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
515 updateSelection(item->mapToScene(itemPos));
518 void ChatScene::updateSelection(const QPointF &pos) {
519 int curRow = rowByScenePos(pos);
520 if(curRow < 0) return;
521 int curColumn = (int)columnByScenePos(pos);
522 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
523 if(minColumn != _selectionMinCol) {
524 _selectionMinCol = minColumn;
525 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
526 _lines[l]->setSelected(true, minColumn);
529 int newstart = qMin(curRow, _firstSelectionRow);
530 int newend = qMax(curRow, _firstSelectionRow);
531 if(newstart < _selectionStart) {
532 for(int l = newstart; l < _selectionStart; l++)
533 _lines[l]->setSelected(true, minColumn);
535 if(newstart > _selectionStart) {
536 for(int l = _selectionStart; l < newstart; l++)
537 _lines[l]->setSelected(false);
539 if(newend > _selectionEnd) {
540 for(int l = _selectionEnd+1; l <= newend; l++)
541 _lines[l]->setSelected(true, minColumn);
543 if(newend < _selectionEnd) {
544 for(int l = newend+1; l <= _selectionEnd; l++)
545 _lines[l]->setSelected(false);
548 _selectionStart = newstart;
549 _selectionEnd = newend;
551 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
552 if(!_selectingItem) {
553 // _selectingItem has been removed already
556 _lines[curRow]->setSelected(false);
557 _isSelecting = false;
558 _selectionStart = -1;
559 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
563 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
564 ChatItem *chatItem = chatItemAt(pos);
567 if(hasGlobalSelection()) {
568 int row = chatItem->row();
569 if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
570 return columnByScenePos(pos) >= _selectionMinCol;
572 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
577 bool ChatScene::isScrollingAllowed() const {
581 // TODO: Handle clicks and single-item selections too
586 /******** MOUSE HANDLING **************************************************************************/
588 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
589 QPointF pos = event->scenePos();
592 // zoom actions and similar
593 chatView()->addActionsToMenu(&menu, pos);
596 if(isPosOverSelection(pos))
597 menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
598 this, SLOT(selectionToClipboard()),
601 // item-specific options (select link etc)
602 ChatItem *item = chatItemAt(pos);
604 item->addActionsToMenu(&menu, item->mapFromScene(pos));
606 // no item -> default scene actions
607 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
609 menu.exec(event->screenPos());
613 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
614 if(event->buttons() == Qt::LeftButton) {
615 if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
616 if(_clickTimer.isActive())
618 if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
619 initiateDrag(event->widget());
621 _clickMode = DragStartClick;
622 handleClick(Qt::LeftButton, _clickPos);
624 _clickMode = NoClick;
627 updateSelection(event->scenePos());
628 emit mouseMoveWhileSelecting(event->scenePos());
630 } else if(_clickHandled && _clickMode < DoubleClick)
631 QGraphicsScene::mouseMoveEvent(event);
633 QGraphicsScene::mouseMoveEvent(event);
636 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
637 if(event->buttons() == Qt::LeftButton) {
638 _leftButtonPressed = true;
639 _clickHandled = false;
640 if(!isPosOverSelection(event->scenePos())) {
641 // immediately clear selection if clicked outside; otherwise, wait for potential drag
644 if(_clickMode != NoClick && _clickTimer.isActive()) {
646 case NoClick: _clickMode = SingleClick; break;
647 case SingleClick: _clickMode = DoubleClick; break;
648 case DoubleClick: _clickMode = TripleClick; break;
649 case TripleClick: _clickMode = DoubleClick; break;
650 case DragStartClick: break;
652 handleClick(Qt::LeftButton, _clickPos);
654 _clickMode = SingleClick;
655 _clickPos = event->scenePos();
659 if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
660 QGraphicsScene::mouseDoubleClickEvent(event);
662 QGraphicsScene::mousePressEvent(event);
665 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
666 // we check for doubleclick ourselves, so just call press handler
667 mousePressEvent(event);
670 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
671 if(event->button() == Qt::LeftButton && _leftButtonPressed) {
672 _leftButtonPressed = false;
673 if(_clickMode != NoClick) {
674 if(_clickMode == SingleClick)
677 if(!_clickTimer.isActive())
678 handleClick(Qt::LeftButton, _clickPos);
680 // no click -> drag or selection move
681 if(isGloballySelecting()) {
682 selectionToClipboard(QClipboard::Selection);
683 _isSelecting = false;
689 QGraphicsScene::mouseReleaseEvent(event);
692 void ChatScene::clickTimeout() {
693 if(!_leftButtonPressed && _clickMode == SingleClick)
694 handleClick(Qt::LeftButton, _clickPos);
697 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
698 if(button == Qt::LeftButton) {
701 // Now send click down to items
702 ChatItem *chatItem = chatItemAt(scenePos);
704 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
706 _clickHandled = true;
710 void ChatScene::initiateDrag(QWidget *source) {
711 QDrag *drag = new QDrag(source);
712 QMimeData *mimeData = new QMimeData;
713 mimeData->setText(selection());
714 drag->setMimeData(mimeData);
716 drag->exec(Qt::CopyAction);
719 /******** SELECTIONS ******************************************************************************/
721 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
725 stringToClipboard(selection(), mode);
728 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode) {
730 // remove trailing linefeeds
731 if(str.endsWith('\n'))
735 case QClipboard::Clipboard:
736 QApplication::clipboard()->setText(str);
738 case QClipboard::Selection:
739 if(QApplication::clipboard()->supportsSelection())
740 QApplication::clipboard()->setText(str, QClipboard::Selection);
747 //!\brief Convert current selection to human-readable string.
748 QString ChatScene::selection() const {
749 //TODO Make selection format configurable!
750 if(hasGlobalSelection()) {
751 int start = qMin(_selectionStart, _selectionEnd);
752 int end = qMax(_selectionStart, _selectionEnd);
753 if(start < 0 || end >= _lines.count()) {
754 qDebug() << "Invalid selection range:" << start << end;
758 for(int l = start; l <= end; l++) {
759 if(_selectionMinCol == ChatLineModel::TimestampColumn)
760 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
761 if(_selectionMinCol <= ChatLineModel::SenderColumn)
762 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
763 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
766 } else if(selectingItem())
767 return selectingItem()->selection();
771 bool ChatScene::hasSelection() const {
772 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
775 bool ChatScene::hasGlobalSelection() const {
776 return _selectionStart >= 0;
779 bool ChatScene::isGloballySelecting() const {
783 void ChatScene::clearGlobalSelection() {
784 if(hasGlobalSelection()) {
785 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
786 _lines[l]->setSelected(false);
787 _isSelecting = false;
788 _selectionStart = -1;
792 void ChatScene::clearSelection() {
793 clearGlobalSelection();
795 selectingItem()->clearSelection();
798 /******** *************************************************************************************/
800 void ChatScene::requestBacklog() {
801 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
803 return filter->requestBacklog();
807 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const {
808 if(x < _firstColHandle->x())
809 return ChatLineModel::TimestampColumn;
810 if(x < _secondColHandle->x())
811 return ChatLineModel::SenderColumn;
813 return ChatLineModel::ContentsColumn;
816 int ChatScene::rowByScenePos(qreal y) const {
817 // This is somewhat hacky... we look at the contents item that is at the given y position, since
818 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
819 // ChatItems cover their ChatLine, so we won't get to the latter directly.
820 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, y)));
821 if(!contentItem) return -1;
822 return contentItem->row();
825 void ChatScene::updateSceneRect(qreal width) {
826 if(_lines.isEmpty()) {
827 updateSceneRect(QRectF(0, 0, width, 0));
831 // we hide day change messages at the top by making the scene rect smaller
832 // and by calling QGraphicsItem::hide() on all leading day change messages
833 // the first one is needed to ensure proper scrollbar ranges
834 // the second for cases where the viewport is larger then the set scenerect
835 // (in this case the items are shown anyways)
836 if(_firstLineRow == -1) {
837 int numRows = model()->rowCount();
839 QModelIndex firstLineIdx;
840 while(_firstLineRow < numRows) {
841 firstLineIdx = model()->index(_firstLineRow, 0);
842 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
844 _lines.at(_firstLineRow)->hide();
849 // the following call should be safe. If it crashes something went wrong during insert/remove
850 if(_firstLineRow < _lines.count()) {
851 ChatLine *firstLine = _lines.at(_firstLineRow);
852 ChatLine *lastLine = _lines.last();
853 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
856 updateSceneRect(QRectF(0, 0, width, 0));
860 void ChatScene::updateSceneRect(const QRectF &rect) {
866 bool ChatScene::event(QEvent *e) {
867 if(e->type() == QEvent::ApplicationPaletteChange) {
868 _firstColHandle->setColor(QApplication::palette().windowText().color());
869 _secondColHandle->setColor(QApplication::palette().windowText().color());
871 return QGraphicsScene::event(e);
874 // ========================================
876 // ========================================
878 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
882 if(webPreview.urlRect != urlRect)
883 webPreview.urlRect = urlRect;
885 if(webPreview.parentItem != parentItem)
886 webPreview.parentItem = parentItem;
888 if(webPreview.url != url) {
889 webPreview.url = url;
890 // prepare to load a different URL
891 if(webPreview.previewItem) {
892 if(webPreview.previewItem->scene())
893 removeItem(webPreview.previewItem);
894 delete webPreview.previewItem;
895 webPreview.previewItem = 0;
897 webPreview.previewState = WebPreview::NoPreview;
900 if(webPreview.url.isEmpty())
903 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
904 switch(webPreview.previewState) {
905 case WebPreview::NoPreview:
906 webPreview.previewState = WebPreview::NewPreview;
907 webPreview.timer.start(500);
909 case WebPreview::NewPreview:
910 case WebPreview::DelayPreview:
911 case WebPreview::ShowPreview:
912 // we're already waiting for the next step or showing the preview
914 case WebPreview::HidePreview:
915 // we still have a valid preview
916 webPreview.previewState = WebPreview::DelayPreview;
917 webPreview.timer.start(1000);
920 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
923 void ChatScene::webPreviewNextStep() {
924 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
925 switch(webPreview.previewState) {
926 case WebPreview::NoPreview:
928 case WebPreview::NewPreview:
929 Q_ASSERT(!webPreview.previewItem);
930 webPreview.previewItem = new WebPreviewItem(webPreview.url);
931 webPreview.previewState = WebPreview::DelayPreview;
932 webPreview.timer.start(1000);
934 case WebPreview::DelayPreview:
935 Q_ASSERT(webPreview.previewItem);
936 // calc position and show
938 qreal previewY = webPreview.urlRect.bottom();
939 qreal previewX = webPreview.urlRect.x();
940 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
941 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
943 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
944 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
946 webPreview.previewItem->setPos(previewX, previewY);
948 addItem(webPreview.previewItem);
949 webPreview.previewState = WebPreview::ShowPreview;
951 case WebPreview::ShowPreview:
952 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
953 qWarning() << "removing preview";
954 if(webPreview.previewItem && webPreview.previewItem->scene())
955 removeItem(webPreview.previewItem);
956 // Fall through to deletion!
957 case WebPreview::HidePreview:
958 if(webPreview.previewItem) {
959 delete webPreview.previewItem;
960 webPreview.previewItem = 0;
962 webPreview.parentItem = 0;
963 webPreview.url = QString();
964 webPreview.urlRect = QRectF();
965 webPreview.previewState = WebPreview::NoPreview;
967 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
970 void ChatScene::clearWebPreview(ChatItem *parentItem) {
971 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
972 switch(webPreview.previewState) {
973 case WebPreview::NewPreview:
974 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
976 case WebPreview::ShowPreview:
977 if(parentItem == 0 || webPreview.parentItem == parentItem) {
978 if(webPreview.previewItem && webPreview.previewItem->scene())
979 removeItem(webPreview.previewItem);
981 // fall through into to set hidden state
982 case WebPreview::DelayPreview:
983 // we're just loading, so haven't shown the preview yet.
984 webPreview.previewState = WebPreview::HidePreview;
985 webPreview.timer.start(5000);
987 case WebPreview::NoPreview:
988 case WebPreview::HidePreview:
991 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
995 // ========================================
996 // end of webkit only
997 // ========================================
999 void ChatScene::showWebPreviewChanged() {
1000 ChatViewSettings settings;
1001 _showWebPreview = settings.showWebPreview();