1 /***************************************************************************
2 * Copyright (C) 2005-2014 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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include <QApplication>
23 #include <QDesktopServices>
25 #include <QGraphicsSceneMouseEvent>
29 #include <QPersistentModelIndex>
44 #include "chatlinemodelitem.h"
45 #include "chatscene.h"
48 #include "clientbacklogmanager.h"
49 #include "columnhandleitem.h"
50 #include "contextmenuactionprovider.h"
51 #include "iconloader.h"
53 #include "markerlineitem.h"
54 #include "messagefilter.h"
56 #include "qtuistyle.h"
57 #include "chatviewsettings.h"
58 #include "webpreviewitem.h"
60 const qreal minContentsWidth = 200;
62 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
63 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
67 _singleBufferId(BufferId()),
68 _sceneRect(0, 0, width, 0),
71 _markerLine(new MarkerLineItem(width)),
72 _markerLineVisible(false),
73 _markerLineValid(false),
74 _markerLineJumpPending(false),
75 _cutoffMode(CutoffRight),
81 _leftButtonPressed(false)
83 MessageFilter *filter = qobject_cast<MessageFilter *>(model);
84 if (filter && filter->isSingleBufferFilter()) {
85 _singleBufferId = filter->singleBufferId();
89 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _markerLine, SLOT(sceneRectChanged(const QRectF &)));
91 ChatViewSettings defaultSettings;
92 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
93 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
95 ChatViewSettings viewSettings(this);
96 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
97 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
99 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
100 addItem(_firstColHandle);
101 _firstColHandle->setXPos(_firstColHandlePos);
102 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
103 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
105 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
106 addItem(_secondColHandle);
107 _secondColHandle->setXPos(_secondColHandlePos);
108 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
110 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
114 if (model->rowCount() > 0)
115 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
117 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
118 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
119 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
120 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
121 connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
122 this, SLOT(rowsRemoved()));
123 connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
126 webPreview.timer.setSingleShot(true);
127 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
129 _showWebPreview = defaultSettings.showWebPreview();
130 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
132 _clickTimer.setInterval(QApplication::doubleClickInterval());
133 _clickTimer.setSingleShot(true);
134 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
136 setItemIndexMethod(QGraphicsScene::NoIndex);
140 ChatScene::~ChatScene()
145 ChatView *ChatScene::chatView() const
151 ColumnHandleItem *ChatScene::firstColumnHandle() const
153 return _firstColHandle;
157 ColumnHandleItem *ChatScene::secondColumnHandle() const
159 return _secondColHandle;
163 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
168 QList<ChatLine *>::ConstIterator start = _lines.begin();
169 QList<ChatLine *>::ConstIterator end = _lines.end();
170 QList<ChatLine *>::ConstIterator middle;
172 int n = int(end - start);
177 middle = start + half;
178 if ((*middle)->msgId() < msgId) {
187 if (start != end && (*start)->msgId() == msgId && (ignoreDayChange ? (*start)->msgType() != Message::DayChange : true))
193 if (start == _lines.begin()) // not (yet?) in our scene
196 // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
198 if (start == end) { // higher than last element
199 if (!ignoreDayChange)
200 return _lines.last();
202 for (int i = _lines.count() -1; i >= 0; i--) {
203 if (_lines.at(i)->msgType() != Message::DayChange)
209 // return the next-lower line
210 if (!ignoreDayChange)
214 if ((*(--start))->msgType() != Message::DayChange)
217 while (start != _lines.begin());
222 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const
224 foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
225 ChatLine *line = qgraphicsitem_cast<ChatLine *>(item);
227 return line->itemAt(line->mapFromScene(scenePos));
233 bool ChatScene::containsBuffer(const BufferId &id) const
235 MessageFilter *filter = qobject_cast<MessageFilter *>(model());
237 return filter->containsBuffer(id);
243 void ChatScene::setMarkerLineVisible(bool visible)
245 _markerLineVisible = visible;
246 if (visible && _markerLineValid)
247 markerLine()->setVisible(true);
249 markerLine()->setVisible(false);
253 void ChatScene::setMarkerLine(MsgId msgId)
255 if (!isSingleBufferScene())
258 if (!msgId.isValid())
259 msgId = Client::markerLine(singleBufferId());
261 if (msgId.isValid()) {
262 ChatLine *line = chatLine(msgId, false, true);
264 markerLine()->setChatLine(line);
265 // if this was the last line, we won't see it because it's outside the sceneRect
266 // .. which is exactly what we want :)
267 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
269 // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
270 if (markerLine()->pos().y() >= sceneRect().y()) {
271 _markerLineValid = true;
272 if (_markerLineVisible)
273 markerLine()->setVisible(true);
274 if (_markerLineJumpPending) {
275 _markerLineJumpPending = false;
276 if (markerLine()->isVisible()) {
277 markerLine()->ensureVisible(QRectF(), 50, 50);
284 _markerLineValid = false;
285 markerLine()->setVisible(false);
289 void ChatScene::jumpToMarkerLine(bool requestBacklog)
291 if (!isSingleBufferScene())
294 if (markerLine()->isVisible()) {
295 markerLine()->ensureVisible(QRectF(), 50, 50);
298 if (!_markerLineValid && requestBacklog) {
299 MsgId msgId = Client::markerLine(singleBufferId());
300 if (msgId.isValid()) {
301 _markerLineJumpPending = true;
302 Client::backlogManager()->requestBacklog(singleBufferId(), msgId, -1, -1, 0);
304 // If we filtered out the lastSeenMsg (by changing filters after setting it), we'd never jump because the above request
305 // won't fetch any prior lines. Thus, trigger a dynamic backlog request just in case, so repeated
306 // jump tries will eventually cause enough backlog to be fetched.
307 // This is a bit hackish, but not wasteful, as jumping to the top of the ChatView would trigger a dynamic fetch anyway.
308 this->requestBacklog();
314 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end)
318 // QModelIndex sidx = model()->index(start, 2);
319 // QModelIndex eidx = model()->index(end, 2);
320 // qDebug() << "rowsInserted:";
322 // QModelIndex ssidx = model()->index(start - 1, 2);
323 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
324 // << ssidx.data(Qt::DisplayRole).toString();
326 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
327 // << sidx.data(Qt::DisplayRole).toString();
328 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
329 // << eidx.data(Qt::DisplayRole).toString();
330 // if(end + 1 < model()->rowCount()) {
331 // QModelIndex eeidx = model()->index(end + 1, 2);
332 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
333 // << eeidx.data(Qt::DisplayRole).toString();
338 qreal width = _sceneRect.width();
339 bool atBottom = (start == _lines.count());
340 bool atTop = !atBottom && (start == 0);
342 if (start < _lines.count()) {
343 y = _lines.value(start)->y();
345 else if (atBottom && !_lines.isEmpty()) {
346 y = _lines.last()->y() + _lines.last()->height();
349 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
350 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
351 qreal timestampWidth = firstColumnHandle()->sceneLeft();
352 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
353 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
356 for (int i = end; i >= start; i--) {
357 ChatLine *line = new ChatLine(i, model(),
359 timestampWidth, senderWidth, contentsWidth,
360 senderPos, contentsPos);
362 line->setPos(0, y-h);
363 _lines.insert(start, line);
368 for (int i = start; i <= end; i++) {
369 ChatLine *line = new ChatLine(i, model(),
371 timestampWidth, senderWidth, contentsWidth,
372 senderPos, contentsPos);
373 line->setPos(0, y+h);
375 _lines.insert(i, line);
380 // update existing items
381 for (int i = end+1; i < _lines.count(); i++) {
382 _lines[i]->setRow(i);
386 if (_selectionStart >= 0) {
387 int offset = end - start + 1;
388 int oldStart = _selectionStart;
389 if (_selectionStart >= start)
390 _selectionStart += offset;
391 if (_selectionEnd >= start) {
392 _selectionEnd += offset;
393 if (_selectionStart == oldStart)
394 for (int i = start; i < start + offset; i++)
395 _lines[i]->setSelected(true);
397 if (_firstSelectionRow >= start)
398 _firstSelectionRow += offset;
401 // neither pre- or append means we have to do dirty work: move items...
402 if (!(atTop || atBottom)) {
404 for (int i = 0; i <= end; i++) {
406 line->setPos(0, line->pos().y() - h);
407 if (line == markerLine()->chatLine())
408 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
412 // check if all went right
413 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
415 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
416 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
417 // 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();
418 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
419 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
423 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
424 // if(end + 1 < _lines.count()) {
425 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
426 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
427 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
428 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
429 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
435 if (start < _firstLineRow) {
436 int prevFirstLineRow = _firstLineRow + (end - start + 1);
437 for (int i = end + 1; i < prevFirstLineRow; i++) {
438 _lines.at(i)->show();
441 // force new search for first proper line
446 emit lastLineChanged(_lines.last(), h);
449 // now move the marker line if necessary. we don't need to do anything if we appended lines though...
450 if (!_markerLineValid)
455 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
459 qreal h = 0; // total height of removed items;
461 bool atTop = (start == 0);
462 bool atBottom = (end == _lines.count() - 1);
465 if (_selectingItem) {
466 int row = _selectingItem->row();
467 if (row >= start && row <= end)
471 // remove items from scene
472 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
473 int lineCount = start;
474 while (lineIter != _lines.end() && lineCount <= end) {
475 if ((*lineIter) == markerLine()->chatLine())
476 markerLine()->setChatLine(0);
477 h += (*lineIter)->height();
479 lineIter = _lines.erase(lineIter);
483 // update rows of remaining chatlines
484 for (int i = start; i < _lines.count(); i++) {
485 _lines.at(i)->setRow(i);
489 if (_selectionStart >= 0) {
490 int offset = end - start + 1;
491 if (_selectionStart >= start)
492 _selectionStart = qMax(_selectionStart - offset, start);
493 if (_selectionEnd >= start)
494 _selectionEnd -= offset;
495 if (_firstSelectionRow >= start)
496 _firstSelectionRow -= offset;
498 if (_selectionEnd < _selectionStart) {
499 _isSelecting = false;
500 _selectionStart = -1;
504 // neither removing at bottom or top means we have to move items...
505 if (!(atTop || atBottom)) {
508 int moveEnd = _lines.count() - 1;
509 if (start < _lines.count() - start) {
519 for (int i = moveStart; i <= moveEnd; i++) {
521 line->setPos(0, line->pos().y() + offset);
525 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
528 // when searching for the first non-date-line we have to take into account that our
529 // model still contains the just removed lines so we cannot simply call updateSceneRect()
530 int numRows = model()->rowCount();
531 QModelIndex firstLineIdx;
533 bool needOffset = false;
536 if (_firstLineRow >= start && _firstLineRow <= end) {
537 _firstLineRow = end + 1;
540 firstLineIdx = model()->index(_firstLineRow, 0);
542 while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
545 _firstLineRow -= end - start + 1;
550 void ChatScene::rowsRemoved()
552 // move the marker line if necessary
557 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br)
559 layout(tl.row(), br.row(), _sceneRect.width());
563 void ChatScene::updateForViewport(qreal width, qreal height)
565 _viewportHeight = height;
570 void ChatScene::setWidth(qreal width)
572 if (width == _sceneRect.width())
574 layout(0, _lines.count()-1, width);
578 void ChatScene::layout(int start, int end, qreal width)
580 // clock_t startT = clock();
582 // disabling the index while doing this complex updates is about
583 // 2 to 10 times faster!
584 //setItemIndexMethod(QGraphicsScene::NoIndex);
588 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
589 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
590 while (row >= start) {
591 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
595 // remaining items don't need geometry changes, but maybe repositioning?
596 ChatLine *line = _lines.at(row);
597 qreal offset = linePos - (line->scenePos().y() + line->height());
600 line = _lines.at(row--);
601 line->setPos(0, line->scenePos().y() + offset);
607 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
609 updateSceneRect(width);
612 emit layoutChanged();
614 // clock_t endT = clock();
615 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
619 void ChatScene::firstHandlePositionChanged(qreal xpos)
621 if (_firstColHandlePos == xpos)
624 _firstColHandlePos = xpos >= 0 ? xpos : 0;
625 ChatViewSettings viewSettings(this);
626 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
627 ChatViewSettings defaultSettings;
628 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
630 // clock_t startT = clock();
632 // disabling the index while doing this complex updates is about
633 // 2 to 10 times faster!
634 //setItemIndexMethod(QGraphicsScene::NoIndex);
636 QList<ChatLine *>::iterator lineIter = _lines.end();
637 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
638 qreal timestampWidth = firstColumnHandle()->sceneLeft();
639 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
640 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
642 while (lineIter != lineIterBegin) {
644 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
646 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
650 // clock_t endT = clock();
651 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
655 void ChatScene::secondHandlePositionChanged(qreal xpos)
657 if (_secondColHandlePos == xpos)
660 _secondColHandlePos = xpos;
661 ChatViewSettings viewSettings(this);
662 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
663 ChatViewSettings defaultSettings;
664 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
666 // clock_t startT = clock();
668 // disabling the index while doing this complex updates is about
669 // 2 to 10 times faster!
670 //setItemIndexMethod(QGraphicsScene::NoIndex);
672 QList<ChatLine *>::iterator lineIter = _lines.end();
673 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
674 qreal linePos = _sceneRect.y() + _sceneRect.height();
675 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
676 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
677 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
678 while (lineIter != lineIterBegin) {
680 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
682 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
686 emit layoutChanged();
688 // clock_t endT = clock();
689 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
693 void ChatScene::setHandleXLimits()
695 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
696 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
701 void ChatScene::setSelectingItem(ChatItem *item)
703 if (_selectingItem) _selectingItem->clearSelection();
704 _selectingItem = item;
708 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos)
710 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
711 _selectionStartCol = _selectionMinCol = item->column();
713 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
714 updateSelection(item->mapToScene(itemPos));
718 void ChatScene::updateSelection(const QPointF &pos)
720 int curRow = rowByScenePos(pos);
721 if (curRow < 0) return;
722 int curColumn = (int)columnByScenePos(pos);
723 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
724 if (minColumn != _selectionMinCol) {
725 _selectionMinCol = minColumn;
726 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
727 _lines[l]->setSelected(true, minColumn);
730 int newstart = qMin(curRow, _firstSelectionRow);
731 int newend = qMax(curRow, _firstSelectionRow);
732 if (newstart < _selectionStart) {
733 for (int l = newstart; l < _selectionStart; l++)
734 _lines[l]->setSelected(true, minColumn);
736 if (newstart > _selectionStart) {
737 for (int l = _selectionStart; l < newstart; l++)
738 _lines[l]->setSelected(false);
740 if (newend > _selectionEnd) {
741 for (int l = _selectionEnd+1; l <= newend; l++)
742 _lines[l]->setSelected(true, minColumn);
744 if (newend < _selectionEnd) {
745 for (int l = newend+1; l <= _selectionEnd; l++)
746 _lines[l]->setSelected(false);
749 _selectionStart = newstart;
750 _selectionEnd = newend;
752 if (newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
753 if (!_selectingItem) {
754 // _selectingItem has been removed already
757 _lines[curRow]->setSelected(false);
758 _isSelecting = false;
759 _selectionStart = -1;
760 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
765 bool ChatScene::isPosOverSelection(const QPointF &pos) const
767 ChatItem *chatItem = chatItemAt(pos);
770 if (hasGlobalSelection()) {
771 int row = chatItem->row();
772 if (row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
773 return columnByScenePos(pos) >= _selectionMinCol;
776 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
782 bool ChatScene::isScrollingAllowed() const
787 // TODO: Handle clicks and single-item selections too
793 /******** MOUSE HANDLING **************************************************************************/
795 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
797 QPointF pos = event->scenePos();
800 // zoom actions and similar
801 chatView()->addActionsToMenu(&menu, pos);
804 // item-specific options (select link etc)
805 ChatItem *item = chatItemAt(pos);
807 item->addActionsToMenu(&menu, item->mapFromScene(pos));
809 // no item -> default scene actions
810 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
812 // If we have text selected, insert the Copy Selection as first item
813 if (isPosOverSelection(pos)) {
814 QAction *sep = menu.insertSeparator(menu.actions().first());
815 QAction *act = new Action(SmallIcon("edit-copy"), tr("Copy Selection"), &menu, this,
816 SLOT(selectionToClipboard()), QKeySequence::Copy);
817 menu.insertAction(sep, act);
819 QString searchSelectionText = selection();
820 if (searchSelectionText.length() > _webSearchSelectionTextMaxVisible)
821 searchSelectionText = searchSelectionText.left(_webSearchSelectionTextMaxVisible).append(QString::fromUtf8("\u2026"));
822 searchSelectionText = tr("Search '%1'").arg(searchSelectionText);
824 menu.addAction(SmallIcon("edit-find"), searchSelectionText, this, SLOT(webSearchOnSelection()));
827 if (QtUi::mainWindow()->menuBar()->isHidden())
828 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
830 menu.exec(event->screenPos());
834 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
836 if (event->buttons() == Qt::LeftButton) {
837 if (!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
838 if (_clickTimer.isActive())
840 if (_clickMode == SingleClick && isPosOverSelection(_clickPos))
841 initiateDrag(event->widget());
843 _clickMode = DragStartClick;
844 handleClick(Qt::LeftButton, _clickPos);
846 _clickMode = NoClick;
849 updateSelection(event->scenePos());
850 emit mouseMoveWhileSelecting(event->scenePos());
853 else if (_clickHandled && _clickMode < DoubleClick)
854 QGraphicsScene::mouseMoveEvent(event);
857 QGraphicsScene::mouseMoveEvent(event);
861 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
863 if (event->buttons() == Qt::LeftButton) {
864 _leftButtonPressed = true;
865 _clickHandled = false;
866 if (!isPosOverSelection(event->scenePos())) {
867 // immediately clear selection if clicked outside; otherwise, wait for potential drag
870 if (_clickMode != NoClick && _clickTimer.isActive()) {
871 switch (_clickMode) {
873 _clickMode = SingleClick; break;
875 _clickMode = DoubleClick; break;
877 _clickMode = TripleClick; break;
879 _clickMode = DoubleClick; break;
883 handleClick(Qt::LeftButton, _clickPos);
886 _clickMode = SingleClick;
887 _clickPos = event->scenePos();
891 if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
892 QGraphicsScene::mouseDoubleClickEvent(event);
894 QGraphicsScene::mousePressEvent(event);
898 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
900 // we check for doubleclick ourselves, so just call press handler
901 mousePressEvent(event);
905 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
907 if (event->button() == Qt::LeftButton && _leftButtonPressed) {
908 _leftButtonPressed = false;
909 if (_clickMode != NoClick) {
910 if (_clickMode == SingleClick)
913 if (!_clickTimer.isActive())
914 handleClick(Qt::LeftButton, _clickPos);
917 // no click -> drag or selection move
918 if (isGloballySelecting()) {
919 selectionToClipboard(QClipboard::Selection);
920 _isSelecting = false;
926 QGraphicsScene::mouseReleaseEvent(event);
930 void ChatScene::clickTimeout()
932 if (!_leftButtonPressed && _clickMode == SingleClick)
933 handleClick(Qt::LeftButton, _clickPos);
937 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos)
939 if (button == Qt::LeftButton) {
942 // Now send click down to items
943 ChatItem *chatItem = chatItemAt(scenePos);
945 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
947 _clickHandled = true;
952 void ChatScene::initiateDrag(QWidget *source)
954 QDrag *drag = new QDrag(source);
955 QMimeData *mimeData = new QMimeData;
956 mimeData->setText(selection());
957 drag->setMimeData(mimeData);
959 drag->exec(Qt::CopyAction);
963 /******** SELECTIONS ******************************************************************************/
965 void ChatScene::selectionToClipboard(QClipboard::Mode mode)
970 stringToClipboard(selection(), mode);
974 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode)
977 // remove trailing linefeeds
978 if (str.endsWith('\n'))
982 case QClipboard::Clipboard:
983 QApplication::clipboard()->setText(str);
985 case QClipboard::Selection:
986 if (QApplication::clipboard()->supportsSelection())
987 QApplication::clipboard()->setText(str, QClipboard::Selection);
995 //!\brief Convert current selection to human-readable string.
996 QString ChatScene::selection() const
998 //TODO Make selection format configurable!
999 if (hasGlobalSelection()) {
1000 int start = qMin(_selectionStart, _selectionEnd);
1001 int end = qMax(_selectionStart, _selectionEnd);
1002 if (start < 0 || end >= _lines.count()) {
1003 qDebug() << "Invalid selection range:" << start << end;
1007 for (int l = start; l <= end; l++) {
1008 if (_selectionMinCol == ChatLineModel::TimestampColumn)
1009 result += _lines[l]->item(ChatLineModel::TimestampColumn)->data(MessageModel::DisplayRole).toString() + " ";
1010 if (_selectionMinCol <= ChatLineModel::SenderColumn)
1011 result += _lines[l]->item(ChatLineModel::SenderColumn)->data(MessageModel::DisplayRole).toString() + " ";
1012 result += _lines[l]->item(ChatLineModel::ContentsColumn)->data(MessageModel::DisplayRole).toString() + "\n";
1016 else if (selectingItem())
1017 return selectingItem()->selection();
1022 bool ChatScene::hasSelection() const
1024 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
1028 bool ChatScene::hasGlobalSelection() const
1030 return _selectionStart >= 0;
1034 bool ChatScene::isGloballySelecting() const
1036 return _isSelecting;
1040 void ChatScene::clearGlobalSelection()
1042 if (hasGlobalSelection()) {
1043 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
1044 _lines[l]->setSelected(false);
1045 _isSelecting = false;
1046 _selectionStart = -1;
1051 void ChatScene::clearSelection()
1053 clearGlobalSelection();
1054 if (selectingItem())
1055 selectingItem()->clearSelection();
1059 /******** *************************************************************************************/
1061 void ChatScene::webSearchOnSelection()
1063 if (!hasSelection())
1066 ChatViewSettings settings;
1067 QString webSearchBaseUrl = settings.webSearchUrlFormatString();
1068 QString webSearchUrl = webSearchBaseUrl.replace(QString("%s"), selection());
1069 QUrl url = QUrl::fromUserInput(webSearchUrl);
1070 QDesktopServices::openUrl(url);
1074 /******** *************************************************************************************/
1076 void ChatScene::requestBacklog()
1078 MessageFilter *filter = qobject_cast<MessageFilter *>(model());
1080 return filter->requestBacklog();
1085 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const
1087 if (x < _firstColHandle->x())
1088 return ChatLineModel::TimestampColumn;
1089 if (x < _secondColHandle->x())
1090 return ChatLineModel::SenderColumn;
1092 return ChatLineModel::ContentsColumn;
1096 int ChatScene::rowByScenePos(qreal y) const
1098 QList<QGraphicsItem *> itemList = items(QPointF(0, y));
1100 // ChatLine should be at the bottom of the list
1101 for (int i = itemList.count()-1; i >= 0; i--) {
1102 ChatLine *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
1110 void ChatScene::updateSceneRect(qreal width)
1112 if (_lines.isEmpty()) {
1113 updateSceneRect(QRectF(0, 0, width, 0));
1117 // we hide day change messages at the top by making the scene rect smaller
1118 // and by calling QGraphicsItem::hide() on all leading day change messages
1119 // the first one is needed to ensure proper scrollbar ranges
1120 // the second for cases where the viewport is larger then the set scenerect
1121 // (in this case the items are shown anyways)
1122 if (_firstLineRow == -1) {
1123 int numRows = model()->rowCount();
1125 QModelIndex firstLineIdx;
1126 while (_firstLineRow < numRows) {
1127 firstLineIdx = model()->index(_firstLineRow, 0);
1128 if ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
1130 _lines.at(_firstLineRow)->hide();
1135 // the following call should be safe. If it crashes something went wrong during insert/remove
1136 if (_firstLineRow < _lines.count()) {
1137 ChatLine *firstLine = _lines.at(_firstLineRow);
1138 ChatLine *lastLine = _lines.last();
1139 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
1143 updateSceneRect(QRectF(0, 0, width, 0));
1148 void ChatScene::updateSceneRect(const QRectF &rect)
1156 // ========================================
1157 // Webkit Only stuff
1158 // ========================================
1160 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect)
1162 if (!_showWebPreview)
1165 if (webPreview.urlRect != urlRect)
1166 webPreview.urlRect = urlRect;
1168 if (webPreview.parentItem != parentItem)
1169 webPreview.parentItem = parentItem;
1171 if (webPreview.url != url) {
1172 webPreview.url = url;
1173 // prepare to load a different URL
1174 if (webPreview.previewItem) {
1175 if (webPreview.previewItem->scene())
1176 removeItem(webPreview.previewItem);
1177 delete webPreview.previewItem;
1178 webPreview.previewItem = 0;
1180 webPreview.previewState = WebPreview::NoPreview;
1183 if (webPreview.url.isEmpty())
1186 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1187 switch (webPreview.previewState) {
1188 case WebPreview::NoPreview:
1189 webPreview.previewState = WebPreview::NewPreview;
1190 webPreview.timer.start(500);
1192 case WebPreview::NewPreview:
1193 case WebPreview::DelayPreview:
1194 case WebPreview::ShowPreview:
1195 // we're already waiting for the next step or showing the preview
1197 case WebPreview::HidePreview:
1198 // we still have a valid preview
1199 webPreview.previewState = WebPreview::DelayPreview;
1200 webPreview.timer.start(1000);
1203 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1207 void ChatScene::webPreviewNextStep()
1209 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1210 switch (webPreview.previewState) {
1211 case WebPreview::NoPreview:
1213 case WebPreview::NewPreview:
1214 Q_ASSERT(!webPreview.previewItem);
1215 webPreview.previewItem = new WebPreviewItem(webPreview.url);
1216 webPreview.previewState = WebPreview::DelayPreview;
1217 webPreview.timer.start(1000);
1219 case WebPreview::DelayPreview:
1220 Q_ASSERT(webPreview.previewItem);
1221 // calc position and show
1223 qreal previewY = webPreview.urlRect.bottom();
1224 qreal previewX = webPreview.urlRect.x();
1225 if (previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
1226 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
1228 if (previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1229 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1231 webPreview.previewItem->setPos(previewX, previewY);
1233 addItem(webPreview.previewItem);
1234 webPreview.previewState = WebPreview::ShowPreview;
1236 case WebPreview::ShowPreview:
1237 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
1238 qWarning() << "removing preview";
1239 if (webPreview.previewItem && webPreview.previewItem->scene())
1240 removeItem(webPreview.previewItem);
1241 // Fall through to deletion!
1242 case WebPreview::HidePreview:
1243 if (webPreview.previewItem) {
1244 delete webPreview.previewItem;
1245 webPreview.previewItem = 0;
1247 webPreview.parentItem = 0;
1248 webPreview.url = QUrl();
1249 webPreview.urlRect = QRectF();
1250 webPreview.previewState = WebPreview::NoPreview;
1252 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1256 void ChatScene::clearWebPreview(ChatItem *parentItem)
1258 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1259 switch (webPreview.previewState) {
1260 case WebPreview::NewPreview:
1261 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
1263 case WebPreview::ShowPreview:
1264 if (parentItem == 0 || webPreview.parentItem == parentItem) {
1265 if (webPreview.previewItem && webPreview.previewItem->scene())
1266 removeItem(webPreview.previewItem);
1268 // fall through into to set hidden state
1269 case WebPreview::DelayPreview:
1270 // we're just loading, so haven't shown the preview yet.
1271 webPreview.previewState = WebPreview::HidePreview;
1272 webPreview.timer.start(5000);
1274 case WebPreview::NoPreview:
1275 case WebPreview::HidePreview:
1278 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1284 // ========================================
1285 // end of webkit only
1286 // ========================================
1288 void ChatScene::showWebPreviewChanged()
1290 ChatViewSettings settings;
1291 _showWebPreview = settings.showWebPreview();