1 /***************************************************************************
2 * Copyright (C) 2005-2010 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>
27 #include <QPersistentModelIndex>
41 #include "chatlinemodelitem.h"
42 #include "chatscene.h"
45 #include "clientbacklogmanager.h"
46 #include "columnhandleitem.h"
47 #include "contextmenuactionprovider.h"
48 #include "iconloader.h"
50 #include "markerlineitem.h"
51 #include "messagefilter.h"
53 #include "qtuistyle.h"
54 #include "chatviewsettings.h"
55 #include "webpreviewitem.h"
57 const qreal minContentsWidth = 200;
59 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
60 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
64 _singleBufferId(BufferId()),
65 _sceneRect(0, 0, width, 0),
68 _markerLine(new MarkerLineItem(width)),
69 _markerLineVisible(false),
70 _markerLineValid(false),
71 _markerLineJumpPending(false),
72 _cutoffMode(CutoffRight),
78 _leftButtonPressed(false)
80 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
81 if(filter && filter->isSingleBufferFilter()) {
82 _singleBufferId = filter->singleBufferId();
86 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _markerLine, SLOT(sceneRectChanged(const QRectF &)));
88 ChatViewSettings defaultSettings;
89 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
90 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
92 ChatViewSettings viewSettings(this);
93 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
94 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
96 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
97 addItem(_firstColHandle);
98 _firstColHandle->setXPos(_firstColHandlePos);
99 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
100 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
102 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
103 addItem(_secondColHandle);
104 _secondColHandle->setXPos(_secondColHandlePos);
105 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
107 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
111 if(model->rowCount() > 0)
112 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
114 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
115 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
116 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
117 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
118 connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
119 this, SLOT(rowsRemoved()));
120 connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
123 webPreview.timer.setSingleShot(true);
124 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
126 _showWebPreview = defaultSettings.showWebPreview();
127 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
129 _clickTimer.setInterval(QApplication::doubleClickInterval());
130 _clickTimer.setSingleShot(true);
131 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
133 setItemIndexMethod(QGraphicsScene::NoIndex);
136 ChatScene::~ChatScene() {
139 ChatView *ChatScene::chatView() const {
143 ColumnHandleItem *ChatScene::firstColumnHandle() const {
144 return _firstColHandle;
147 ColumnHandleItem *ChatScene::secondColumnHandle() const {
148 return _secondColHandle;
151 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const {
155 QList<ChatLine*>::ConstIterator start = _lines.begin();
156 QList<ChatLine*>::ConstIterator end = _lines.end();
157 QList<ChatLine*>::ConstIterator middle;
159 int n = int(end - start);
164 middle = start + half;
165 if((*middle)->msgId() < msgId) {
173 if(start != end && (*start)->msgId() == msgId && (ignoreDayChange? (*start)->msgType() != Message::DayChange : true))
179 if(start == _lines.begin()) // not (yet?) in our scene
182 // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
184 if(start == end) { // higher than last element
186 return _lines.last();
188 for(int i = _lines.count() -1; i >= 0; i--) {
189 if(_lines.at(i)->msgType() != Message::DayChange)
195 // return the next-lower line
200 if((*(--start))->msgType() != Message::DayChange)
202 } while(start != _lines.begin());
206 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
207 foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
208 ChatLine *line = qgraphicsitem_cast<ChatLine*>(item);
210 return line->itemAt(line->mapFromScene(scenePos));
215 bool ChatScene::containsBuffer(const BufferId &id) const {
216 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
218 return filter->containsBuffer(id);
223 void ChatScene::setMarkerLineVisible(bool visible) {
224 _markerLineVisible = visible;
225 if(visible && _markerLineValid)
226 markerLine()->setVisible(true);
228 markerLine()->setVisible(false);
231 void ChatScene::setMarkerLine(MsgId msgId) {
232 if(!isSingleBufferScene())
236 msgId = Client::markerLine(singleBufferId());
238 if(msgId.isValid()) {
239 ChatLine *line = chatLine(msgId, false, true);
241 markerLine()->setChatLine(line);
242 // if this was the last line, we won't see it because it's outside the sceneRect
243 // .. which is exactly what we want :)
244 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
246 // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
247 if(markerLine()->pos().y() >= sceneRect().y()) {
248 _markerLineValid = true;
249 if(_markerLineVisible)
250 markerLine()->setVisible(true);
251 if(_markerLineJumpPending) {
252 _markerLineJumpPending = false;
253 if(markerLine()->isVisible()) {
254 markerLine()->ensureVisible(QRectF(), 50, 50);
261 _markerLineValid = false;
262 markerLine()->setVisible(false);
265 void ChatScene::jumpToMarkerLine(bool requestBacklog) {
266 if(!isSingleBufferScene())
269 if(markerLine()->isVisible()) {
270 markerLine()->ensureVisible(QRectF(), 50, 50);
273 if(!_markerLineValid && requestBacklog) {
274 MsgId msgId = Client::markerLine(singleBufferId());
275 if(msgId.isValid()) {
276 _markerLineJumpPending = true;
277 Client::backlogManager()->requestBacklog(singleBufferId(), msgId, -1, -1, 0);
279 // If we filtered out the lastSeenMsg (by changing filters after setting it), we'd never jump because the above request
280 // won't fetch any prior lines. Thus, trigger a dynamic backlog request just in case, so repeated
281 // jump tries will eventually cause enough backlog to be fetched.
282 // This is a bit hackish, but not wasteful, as jumping to the top of the ChatView would trigger a dynamic fetch anyway.
283 this->requestBacklog();
288 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
291 // QModelIndex sidx = model()->index(start, 2);
292 // QModelIndex eidx = model()->index(end, 2);
293 // qDebug() << "rowsInserted:";
295 // QModelIndex ssidx = model()->index(start - 1, 2);
296 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
297 // << ssidx.data(Qt::DisplayRole).toString();
299 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
300 // << sidx.data(Qt::DisplayRole).toString();
301 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
302 // << eidx.data(Qt::DisplayRole).toString();
303 // if(end + 1 < model()->rowCount()) {
304 // QModelIndex eeidx = model()->index(end + 1, 2);
305 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
306 // << eeidx.data(Qt::DisplayRole).toString();
311 qreal width = _sceneRect.width();
312 bool atBottom = (start == _lines.count());
313 bool atTop = !atBottom && (start == 0);
315 if(start < _lines.count()) {
316 y = _lines.value(start)->y();
317 } else if(atBottom && !_lines.isEmpty()) {
318 y = _lines.last()->y() + _lines.last()->height();
321 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
322 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
323 qreal timestampWidth = firstColumnHandle()->sceneLeft();
324 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
325 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
328 for(int i = end; i >= start; i--) {
329 ChatLine *line = new ChatLine(i, model(),
331 timestampWidth, senderWidth, contentsWidth,
332 senderPos, contentsPos);
334 line->setPos(0, y-h);
335 _lines.insert(start, line);
339 for(int i = start; i <= end; i++) {
340 ChatLine *line = new ChatLine(i, model(),
342 timestampWidth, senderWidth, contentsWidth,
343 senderPos, contentsPos);
344 line->setPos(0, y+h);
346 _lines.insert(i, line);
351 // update existing items
352 for(int i = end+1; i < _lines.count(); i++) {
353 _lines[i]->setRow(i);
357 if(_selectionStart >= 0) {
358 int offset = end - start + 1;
359 int oldStart = _selectionStart;
360 if(_selectionStart >= start)
361 _selectionStart += offset;
362 if(_selectionEnd >= start) {
363 _selectionEnd += offset;
364 if(_selectionStart == oldStart)
365 for(int i = start; i < start + offset; i++)
366 _lines[i]->setSelected(true);
368 if(_firstSelectionRow >= start)
369 _firstSelectionRow += offset;
372 // neither pre- or append means we have to do dirty work: move items...
373 if(!(atTop || atBottom)) {
375 for(int i = 0; i <= end; i++) {
377 line->setPos(0, line->pos().y() - h);
378 if(line == markerLine()->chatLine())
379 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
383 // check if all went right
384 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
386 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
387 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
388 // 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();
389 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
390 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
394 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
395 // if(end + 1 < _lines.count()) {
396 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
397 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
398 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
399 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
400 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
406 if(start < _firstLineRow) {
407 int prevFirstLineRow = _firstLineRow + (end - start + 1);
408 for(int i = end + 1; i < prevFirstLineRow; i++) {
409 _lines.at(i)->show();
412 // force new search for first proper line
417 emit lastLineChanged(_lines.last(), h);
420 // now move the marker line if necessary. we don't need to do anything if we appended lines though...
421 if(!_markerLineValid)
425 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
428 qreal h = 0; // total height of removed items;
430 bool atTop = (start == 0);
431 bool atBottom = (end == _lines.count() - 1);
432 bool moveTop = false;
436 int row = _selectingItem->row();
437 if(row >= start && row <= end)
441 // remove items from scene
442 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
443 int lineCount = start;
444 while(lineIter != _lines.end() && lineCount <= end) {
445 if((*lineIter) == markerLine()->chatLine())
446 markerLine()->setChatLine(0);
447 h += (*lineIter)->height();
449 lineIter = _lines.erase(lineIter);
453 // update rows of remaining chatlines
454 for(int i = start; i < _lines.count(); i++) {
455 _lines.at(i)->setRow(i);
459 if(_selectionStart >= 0) {
460 int offset = end - start + 1;
461 if(_selectionStart >= start)
462 _selectionStart = qMax(_selectionStart -= offset, start);
463 if(_selectionEnd >= start)
464 _selectionEnd -= offset;
465 if(_firstSelectionRow >= start)
466 _firstSelectionRow -= offset;
468 if(_selectionEnd < _selectionStart) {
469 _isSelecting = false;
470 _selectionStart = -1;
474 // neither removing at bottom or top means we have to move items...
475 if(!(atTop || atBottom)) {
478 int moveEnd = _lines.count() - 1;
479 if(start < _lines.count() - start) {
489 for(int i = moveStart; i <= moveEnd; i++) {
491 line->setPos(0, line->pos().y() + offset);
495 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
498 // when searching for the first non-date-line we have to take into account that our
499 // model still contains the just removed lines so we cannot simply call updateSceneRect()
500 int numRows = model()->rowCount();
501 QModelIndex firstLineIdx;
503 bool needOffset = false;
506 if(_firstLineRow >= start && _firstLineRow <= end) {
507 _firstLineRow = end + 1;
510 firstLineIdx = model()->index(_firstLineRow, 0);
511 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
514 _firstLineRow -= end - start + 1;
518 void ChatScene::rowsRemoved() {
519 // move the marker line if necessary
523 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br) {
524 layout(tl.row(), br.row(), _sceneRect.width());
527 void ChatScene::updateForViewport(qreal width, qreal height) {
528 _viewportHeight = height;
532 void ChatScene::setWidth(qreal width) {
533 if(width == _sceneRect.width())
535 layout(0, _lines.count()-1, width);
538 void ChatScene::layout(int start, int end, qreal width) {
539 // clock_t startT = clock();
541 // disabling the index while doing this complex updates is about
542 // 2 to 10 times faster!
543 //setItemIndexMethod(QGraphicsScene::NoIndex);
547 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
548 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
549 while(row >= start) {
550 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
554 // remaining items don't need geometry changes, but maybe repositioning?
555 ChatLine *line = _lines.at(row);
556 qreal offset = linePos - (line->scenePos().y() + line->height());
559 line = _lines.at(row--);
560 line->setPos(0, line->scenePos().y() + offset);
566 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
568 updateSceneRect(width);
571 emit layoutChanged();
573 // clock_t endT = clock();
574 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
577 void ChatScene::firstHandlePositionChanged(qreal xpos) {
578 if(_firstColHandlePos == xpos)
581 _firstColHandlePos = xpos >= 0 ? xpos : 0;
582 ChatViewSettings viewSettings(this);
583 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
584 ChatViewSettings defaultSettings;
585 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
587 // clock_t startT = clock();
589 // disabling the index while doing this complex updates is about
590 // 2 to 10 times faster!
591 //setItemIndexMethod(QGraphicsScene::NoIndex);
593 QList<ChatLine *>::iterator lineIter = _lines.end();
594 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
595 qreal timestampWidth = firstColumnHandle()->sceneLeft();
596 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
597 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
599 while(lineIter != lineIterBegin) {
601 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
603 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
607 // clock_t endT = clock();
608 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
611 void ChatScene::secondHandlePositionChanged(qreal xpos) {
612 if(_secondColHandlePos == xpos)
615 _secondColHandlePos = xpos;
616 ChatViewSettings viewSettings(this);
617 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
618 ChatViewSettings defaultSettings;
619 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
621 // clock_t startT = clock();
623 // disabling the index while doing this complex updates is about
624 // 2 to 10 times faster!
625 //setItemIndexMethod(QGraphicsScene::NoIndex);
627 QList<ChatLine *>::iterator lineIter = _lines.end();
628 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
629 qreal linePos = _sceneRect.y() + _sceneRect.height();
630 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
631 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
632 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
633 while(lineIter != lineIterBegin) {
635 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
637 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
641 emit layoutChanged();
643 // clock_t endT = clock();
644 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
647 void ChatScene::setHandleXLimits() {
648 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
649 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
653 void ChatScene::setSelectingItem(ChatItem *item) {
654 if(_selectingItem) _selectingItem->clearSelection();
655 _selectingItem = item;
658 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
659 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
660 _selectionStartCol = _selectionMinCol = item->column();
662 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
663 updateSelection(item->mapToScene(itemPos));
666 void ChatScene::updateSelection(const QPointF &pos) {
667 int curRow = rowByScenePos(pos);
668 if(curRow < 0) return;
669 int curColumn = (int)columnByScenePos(pos);
670 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
671 if(minColumn != _selectionMinCol) {
672 _selectionMinCol = minColumn;
673 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
674 _lines[l]->setSelected(true, minColumn);
677 int newstart = qMin(curRow, _firstSelectionRow);
678 int newend = qMax(curRow, _firstSelectionRow);
679 if(newstart < _selectionStart) {
680 for(int l = newstart; l < _selectionStart; l++)
681 _lines[l]->setSelected(true, minColumn);
683 if(newstart > _selectionStart) {
684 for(int l = _selectionStart; l < newstart; l++)
685 _lines[l]->setSelected(false);
687 if(newend > _selectionEnd) {
688 for(int l = _selectionEnd+1; l <= newend; l++)
689 _lines[l]->setSelected(true, minColumn);
691 if(newend < _selectionEnd) {
692 for(int l = newend+1; l <= _selectionEnd; l++)
693 _lines[l]->setSelected(false);
696 _selectionStart = newstart;
697 _selectionEnd = newend;
699 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
700 if(!_selectingItem) {
701 // _selectingItem has been removed already
704 _lines[curRow]->setSelected(false);
705 _isSelecting = false;
706 _selectionStart = -1;
707 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
711 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
712 ChatItem *chatItem = chatItemAt(pos);
715 if(hasGlobalSelection()) {
716 int row = chatItem->row();
717 if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
718 return columnByScenePos(pos) >= _selectionMinCol;
720 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
725 bool ChatScene::isScrollingAllowed() const {
729 // TODO: Handle clicks and single-item selections too
734 /******** MOUSE HANDLING **************************************************************************/
736 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
737 QPointF pos = event->scenePos();
740 // zoom actions and similar
741 chatView()->addActionsToMenu(&menu, pos);
744 if(isPosOverSelection(pos))
745 menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
746 this, SLOT(selectionToClipboard()),
749 // item-specific options (select link etc)
750 ChatItem *item = chatItemAt(pos);
752 item->addActionsToMenu(&menu, item->mapFromScene(pos));
754 // no item -> default scene actions
755 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
757 if (QtUi::mainWindow()->menuBar()->isHidden())
758 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
760 menu.exec(event->screenPos());
764 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
765 if(event->buttons() == Qt::LeftButton) {
766 if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
767 if(_clickTimer.isActive())
769 if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
770 initiateDrag(event->widget());
772 _clickMode = DragStartClick;
773 handleClick(Qt::LeftButton, _clickPos);
775 _clickMode = NoClick;
778 updateSelection(event->scenePos());
779 emit mouseMoveWhileSelecting(event->scenePos());
781 } else if(_clickHandled && _clickMode < DoubleClick)
782 QGraphicsScene::mouseMoveEvent(event);
784 QGraphicsScene::mouseMoveEvent(event);
787 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
788 if(event->buttons() == Qt::LeftButton) {
789 _leftButtonPressed = true;
790 _clickHandled = false;
791 if(!isPosOverSelection(event->scenePos())) {
792 // immediately clear selection if clicked outside; otherwise, wait for potential drag
795 if(_clickMode != NoClick && _clickTimer.isActive()) {
797 case NoClick: _clickMode = SingleClick; break;
798 case SingleClick: _clickMode = DoubleClick; break;
799 case DoubleClick: _clickMode = TripleClick; break;
800 case TripleClick: _clickMode = DoubleClick; break;
801 case DragStartClick: break;
803 handleClick(Qt::LeftButton, _clickPos);
805 _clickMode = SingleClick;
806 _clickPos = event->scenePos();
810 if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
811 QGraphicsScene::mouseDoubleClickEvent(event);
813 QGraphicsScene::mousePressEvent(event);
816 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
817 // we check for doubleclick ourselves, so just call press handler
818 mousePressEvent(event);
821 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
822 if(event->button() == Qt::LeftButton && _leftButtonPressed) {
823 _leftButtonPressed = false;
824 if(_clickMode != NoClick) {
825 if(_clickMode == SingleClick)
828 if(!_clickTimer.isActive())
829 handleClick(Qt::LeftButton, _clickPos);
831 // no click -> drag or selection move
832 if(isGloballySelecting()) {
833 selectionToClipboard(QClipboard::Selection);
834 _isSelecting = false;
840 QGraphicsScene::mouseReleaseEvent(event);
843 void ChatScene::clickTimeout() {
844 if(!_leftButtonPressed && _clickMode == SingleClick)
845 handleClick(Qt::LeftButton, _clickPos);
848 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
849 if(button == Qt::LeftButton) {
852 // Now send click down to items
853 ChatItem *chatItem = chatItemAt(scenePos);
855 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
857 _clickHandled = true;
861 void ChatScene::initiateDrag(QWidget *source) {
862 QDrag *drag = new QDrag(source);
863 QMimeData *mimeData = new QMimeData;
864 mimeData->setText(selection());
865 drag->setMimeData(mimeData);
867 drag->exec(Qt::CopyAction);
870 /******** SELECTIONS ******************************************************************************/
872 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
876 stringToClipboard(selection(), mode);
879 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode) {
881 // remove trailing linefeeds
882 if(str.endsWith('\n'))
886 case QClipboard::Clipboard:
887 QApplication::clipboard()->setText(str);
889 case QClipboard::Selection:
890 if(QApplication::clipboard()->supportsSelection())
891 QApplication::clipboard()->setText(str, QClipboard::Selection);
898 //!\brief Convert current selection to human-readable string.
899 QString ChatScene::selection() const {
900 //TODO Make selection format configurable!
901 if(hasGlobalSelection()) {
902 int start = qMin(_selectionStart, _selectionEnd);
903 int end = qMax(_selectionStart, _selectionEnd);
904 if(start < 0 || end >= _lines.count()) {
905 qDebug() << "Invalid selection range:" << start << end;
909 for(int l = start; l <= end; l++) {
910 if(_selectionMinCol == ChatLineModel::TimestampColumn)
911 result += _lines[l]->item(ChatLineModel::TimestampColumn)->data(MessageModel::DisplayRole).toString() + " ";
912 if(_selectionMinCol <= ChatLineModel::SenderColumn)
913 result += _lines[l]->item(ChatLineModel::SenderColumn)->data(MessageModel::DisplayRole).toString() + " ";
914 result += _lines[l]->item(ChatLineModel::ContentsColumn)->data(MessageModel::DisplayRole).toString() + "\n";
917 } else if(selectingItem())
918 return selectingItem()->selection();
922 bool ChatScene::hasSelection() const {
923 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
926 bool ChatScene::hasGlobalSelection() const {
927 return _selectionStart >= 0;
930 bool ChatScene::isGloballySelecting() const {
934 void ChatScene::clearGlobalSelection() {
935 if(hasGlobalSelection()) {
936 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
937 _lines[l]->setSelected(false);
938 _isSelecting = false;
939 _selectionStart = -1;
943 void ChatScene::clearSelection() {
944 clearGlobalSelection();
946 selectingItem()->clearSelection();
949 /******** *************************************************************************************/
951 void ChatScene::requestBacklog() {
952 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
954 return filter->requestBacklog();
958 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const {
959 if(x < _firstColHandle->x())
960 return ChatLineModel::TimestampColumn;
961 if(x < _secondColHandle->x())
962 return ChatLineModel::SenderColumn;
964 return ChatLineModel::ContentsColumn;
967 int ChatScene::rowByScenePos(qreal y) const {
968 QList<QGraphicsItem*> itemList = items(QPointF(0, y));
970 // ChatLine should be at the bottom of the list
971 for(int i = itemList.count()-1; i >= 0; i--) {
972 ChatLine *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
979 void ChatScene::updateSceneRect(qreal width) {
980 if(_lines.isEmpty()) {
981 updateSceneRect(QRectF(0, 0, width, 0));
985 // we hide day change messages at the top by making the scene rect smaller
986 // and by calling QGraphicsItem::hide() on all leading day change messages
987 // the first one is needed to ensure proper scrollbar ranges
988 // the second for cases where the viewport is larger then the set scenerect
989 // (in this case the items are shown anyways)
990 if(_firstLineRow == -1) {
991 int numRows = model()->rowCount();
993 QModelIndex firstLineIdx;
994 while(_firstLineRow < numRows) {
995 firstLineIdx = model()->index(_firstLineRow, 0);
996 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
998 _lines.at(_firstLineRow)->hide();
1003 // the following call should be safe. If it crashes something went wrong during insert/remove
1004 if(_firstLineRow < _lines.count()) {
1005 ChatLine *firstLine = _lines.at(_firstLineRow);
1006 ChatLine *lastLine = _lines.last();
1007 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
1010 updateSceneRect(QRectF(0, 0, width, 0));
1014 void ChatScene::updateSceneRect(const QRectF &rect) {
1020 // ========================================
1021 // Webkit Only stuff
1022 // ========================================
1024 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect) {
1025 if(!_showWebPreview)
1028 if(webPreview.urlRect != urlRect)
1029 webPreview.urlRect = urlRect;
1031 if(webPreview.parentItem != parentItem)
1032 webPreview.parentItem = parentItem;
1034 if(webPreview.url != url) {
1035 webPreview.url = url;
1036 // prepare to load a different URL
1037 if(webPreview.previewItem) {
1038 if(webPreview.previewItem->scene())
1039 removeItem(webPreview.previewItem);
1040 delete webPreview.previewItem;
1041 webPreview.previewItem = 0;
1043 webPreview.previewState = WebPreview::NoPreview;
1046 if(webPreview.url.isEmpty())
1049 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1050 switch(webPreview.previewState) {
1051 case WebPreview::NoPreview:
1052 webPreview.previewState = WebPreview::NewPreview;
1053 webPreview.timer.start(500);
1055 case WebPreview::NewPreview:
1056 case WebPreview::DelayPreview:
1057 case WebPreview::ShowPreview:
1058 // we're already waiting for the next step or showing the preview
1060 case WebPreview::HidePreview:
1061 // we still have a valid preview
1062 webPreview.previewState = WebPreview::DelayPreview;
1063 webPreview.timer.start(1000);
1066 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1069 void ChatScene::webPreviewNextStep() {
1070 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1071 switch(webPreview.previewState) {
1072 case WebPreview::NoPreview:
1074 case WebPreview::NewPreview:
1075 Q_ASSERT(!webPreview.previewItem);
1076 webPreview.previewItem = new WebPreviewItem(webPreview.url);
1077 webPreview.previewState = WebPreview::DelayPreview;
1078 webPreview.timer.start(1000);
1080 case WebPreview::DelayPreview:
1081 Q_ASSERT(webPreview.previewItem);
1082 // calc position and show
1084 qreal previewY = webPreview.urlRect.bottom();
1085 qreal previewX = webPreview.urlRect.x();
1086 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
1087 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
1089 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1090 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1092 webPreview.previewItem->setPos(previewX, previewY);
1094 addItem(webPreview.previewItem);
1095 webPreview.previewState = WebPreview::ShowPreview;
1097 case WebPreview::ShowPreview:
1098 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
1099 qWarning() << "removing preview";
1100 if(webPreview.previewItem && webPreview.previewItem->scene())
1101 removeItem(webPreview.previewItem);
1102 // Fall through to deletion!
1103 case WebPreview::HidePreview:
1104 if(webPreview.previewItem) {
1105 delete webPreview.previewItem;
1106 webPreview.previewItem = 0;
1108 webPreview.parentItem = 0;
1109 webPreview.url = QUrl();
1110 webPreview.urlRect = QRectF();
1111 webPreview.previewState = WebPreview::NoPreview;
1113 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1116 void ChatScene::clearWebPreview(ChatItem *parentItem) {
1117 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1118 switch(webPreview.previewState) {
1119 case WebPreview::NewPreview:
1120 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
1122 case WebPreview::ShowPreview:
1123 if(parentItem == 0 || webPreview.parentItem == parentItem) {
1124 if(webPreview.previewItem && webPreview.previewItem->scene())
1125 removeItem(webPreview.previewItem);
1127 // fall through into to set hidden state
1128 case WebPreview::DelayPreview:
1129 // we're just loading, so haven't shown the preview yet.
1130 webPreview.previewState = WebPreview::HidePreview;
1131 webPreview.timer.start(5000);
1133 case WebPreview::NoPreview:
1134 case WebPreview::HidePreview:
1137 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1141 // ========================================
1142 // end of webkit only
1143 // ========================================
1145 void ChatScene::showWebPreviewChanged() {
1146 ChatViewSettings settings;
1147 _showWebPreview = settings.showWebPreview();